Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Java Collectors class provides various methods to deal with elements.
It is used to accumulate elements into a list. It will create a new list (It will not change the current list).
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toList());
// output: [1,4,9,16,25,36,36]
It is used to accumulate elements into a set, It will remove all the duplicate entries.
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toSet());
// output: [1,4,9,16,25,36]
We can accumulate data in any specific collection as well.
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers
.stream()
.filter(x -> x >2)
.collect(Collectors.toCollection(LinkedList::new));
// output: [3,4,5,6,6]
Here we are accumulating elements in a linked list.
#java-programming #java #functional-programming #java-8-feature #collector