您的第三次尝试很接近,尽管书面没有编译。该方法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; }
}
然后,为了将它们收集到SortedSetvia中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.toCollectionCollectors.toListCollectors.toSet。