按流排序不适用



我有一段Java8代码:

Set<Purchase> purchases = 
user.getAcquisitions()
.parallelStream()
.map(a -> a.getPurchases())
.sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed());

但我有这个编译错误,我不知道为什么:

The method sorted(Comparator<? super Set<Purchase>>) in the type Stream<Set<Purchase>> is not applicable for the arguments 
(Comparator<Purchase>)

.map(a -> a.getPurchases())之后,您似乎期待着一个Stream<Purchase>,但实际拥有的是一个Stream<Set<Purchase>>

如果Stream<Purchase>确实是您想要的,那么您应该使用

.flatMap(a -> a.getPurchases().stream())

为了扩展Joe的答案,似乎你想要一个按排序的Set<Purchase>(无论出于什么原因(,只要你有充分的理由这样做,在这种情况下你可以使用LinkedHashSet:

user.getAcquisitions()
.parallelStream()
.flatMap(e -> e.getPurchase().stream())
.sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed())
.collect(toCollection(LinkedHashSet::new));
  • flatMap将嵌套的Set<Purchase>展平为Stream<Purchase>
  • 然后,它根据提供的比较器对元素进行排序
  • 然后将元素收集到尊重插入顺序的CCD_ 10实现中

btw注意,你也可以只做:

user.getAcquisitions()
.parallelStream()
.flatMap(e -> e.getPurchase().stream())
.distinct()
.sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed())
.collect(toCollection(ArrayList::new));

因此,根据您使用的上下文,您最好将结果元素收集到列表实现中。

  • flatMap将嵌套的Set<Purchase>展平为Stream<Purchase>
  • distinct根据equals方法返回新的唯一对象流
  • 然后,它根据提供的比较器对元素进行排序
  • 最后,它将流中的元素收集到ArrayList实现中

a.getPurchases((给您一个集合,您的比较器比较的是集合中的元素,而不是集合。

根据你的预期产量,我知道你想得到最新购买日期的那套。如果每套只包含相同的购买日期,你可以创建这样的比较器:

.sorted(Comparator.comparing(purchases -> purchases.iterator().next(), (p1, p2) -> -p1.compareTo(p2)));

如果一套内的购买日期不同,你需要得到一套内最大(或最小(购买日期,然后比较两套内的日期,比如:

final Stream<Set<Purchase>> sorted = acquisitions.stream()
.map(Acquisition::getPurchases)
.sorted(Comparator.comparing(purchases ->
Collections.max(purchases, Comparator.comparing(Purchase::getPurchaseDate)).getPurchaseDate(),
(date1, date2) -> -date1.compareTo(date2)));

试着这样做:

Set<Purchase> purchases = 
user.getAcquisitions()
.parallelStream()
.map(Acquisition::getPurchases)
.flatMap(Set::stream)
.collect(Collectors.toCollection(TreeSet::new));

最新更新