您的第三次尝试很接近,尽管书面没有编译。该方法Collectors.toCollection
采用 aSupplier
返回所需的Collection
,而不是Collection
本身。
如果MyData
定义为:
public class MyData {
private Instant instant;
public Instant getInstant() { return instant; }
public void setInstant(Instant instant) { this.instant = instant; }
}
然后,为了将它们收集到SortedSet
via中Stream
,您可以执行以下操作:
Comparator<MyData> comparator = Comparator.comparing(MyData::getInstant);
TreeSet<MyData> set = getMyData().stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(comparator));
请注意,我不在Stream.sorted
这里使用。如果您要使用它实际上是有害的Stream.sorted
,因为它增加了无助于最终结果的工作。将Stream
对其元素进行排序,然后开始将它们添加到TreeSet
其中也将对元素进行排序。
也就是说,在某些情况下 usingStream.sorted
是有益的:当Stream.collect
返回Collection
保证插入顺序的 a 时。ALinkedHashSet
以及 , 的任何实现List
保证插入顺序。所以你可以这样做:
LinkedHashSet<MyData> set = getMyData().stream()
.sorted(comparator)
.collect(Collectors.toCollection(LinkedHashSet::new));
// Or use a List
List<MyData> list = getMyData().stream()
.distinct() // If you want only unique elements in the end List
.sorted(comparator)
.collect(Collectors.toList());
Collection
注意:端保证插入顺序是不够的。被使用的Collector
不能以无序为特征。和Collector
返回的 s就是这种情况。使用时并非如此Collectors.toCollection
Collectors.toList
Collectors.toSet
。