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

Collectors.toSet() does not preserve order. I could use Lists instead, but I want to indicate that the resulting collection does not allow element duplication, which is exactly what Set interface is for.

31267 次浏览

您可以使用 toCollection并提供所需集的具体实例。例如,如果要保持插入顺序:

Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));

例如:

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