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.
If you have an ordered stream and perform operations which guarantee to maintain the order, it doesn't matter whether the stream is processed in parallel or sequential; the implementation will maintain the order. The ordered property is distinct from parallel vs sequential.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
You can use toCollection
and provide the concrete instance of the set you want. For example if you want to keep insertion order:
Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));
For example:
public class Test {
public static final void main(String[] args) {
List<String> list = Arrays.asList("b", "c", "a");
Set<String> linkedSet =
list.stream().collect(Collectors.toCollection(LinkedHashSet::new));
Set<String> collectorToSet =
list.stream().collect(Collectors.toSet());
System.out.println(linkedSet); //[b, c, a]
System.out.println(collectorToSet); //[a, b, c]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With