Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Collector that collects to an order-preserving Set?

People also ask

What is collectors in java?

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.

Does stream preserve order?

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.

What is stream function in java?

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]
    }
}