Using Collector for Collection

Java-Using Collector for Collection

Using Collector for Collection

The stream API provides the another form of collect( ) method. This method is used to obtain a collection from a stream using Collector interface. It has the following form:

Using Collector for Collection

Here, R specifies the type of the result, and T specifies the element type of the invoking stream. The internal accumulated type is specified by A. The collector specifies how the collection process works. The collect( ) method is a terminal operation. The Collector interface is declared in java.util.stream and it specifies several methods.

Collectors class

We won’t need to implement the Collector interface. Instead, we will use the predefined collectors that are provided by the Collectors class, which is packaged in java.util.stream. The Collectors class provides a large number of static methods for common collectors.

The toList and toSet Methods

The toList( ) and toSet( ) static methods of the Collectors class returns a Collector that can be used to collect elements into a List and Set.

Collection From a Stream


The toCollection Method

If you want to get a specific type collection, use the toCollection method of Collectors with that type object or constructor reference.

Collection From a Stream


The joining Method

Suppose you want to collect all strings in a stream by concatenating them. You can use the Collectors.joining() method. The joining method has three forms:

Collection From a Stream


Object to String

If your stream contains objects other than strings, suppose you want to collect all object description strings in the stream by concatenating them, you need to first convert them to strings. To convert to strings use the map((e)->e.toString()) or map(Object::toString) and then call joining().

Collection From a Stream

Program

Using Collector for Collection

Program Source

import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;

public class Javaapp {

    public static void main(String[] args) {

        Stream<Integer> istm = Stream.of(10,20,30,40,50);
        List<Integer> list = istm.collect(Collectors.toList());
        System.out.println("list->   "+list);
        
        istm = Stream.of(10,20,30,40,50);
        ArrayList<Integer> arylst = istm.collect(Collectors.toCollection(ArrayList::new));
        System.out.println("arylst-> "+arylst);
        
        Stream<String> strstm = Stream.of("One","Two","Three","Four","Five");
        String str = strstm.collect(Collectors.joining("--","[-","-]"));
        System.out.println("str->    "+str);
    } 
}

Leave a Comment