Java流按两个字段排序

7

我有一组需要按照两个参数排序的项目列表,第一个参数是orderIndex,我已经成功地实现了它(请参见下面的代码),第二个参数是amount。因此,基本上第一项应该是具有最低orderIndex的项,并且它们需要按amount排序。

result.stream().sorted { s1, s2 -> s1.intervalType.orderIndex.compareTo(s2.intervalType.orderIndex) }.collect(Collectors.toList())

目前我有这段代码,它只按照orderIndex排序,第二个参数amount位于s1.item.amount。

有什么想法可以用第二个排序参数升级这个代码吗?

我找到了这个例子。

persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

我的问题是,如何访问Person对象中的其他对象。例如,在我正在排序的对象中有一个IntervalType对象,我需要使用intervalType.orderIndex。

注意:

只需注意,我需要在Kotlin中而不是Java中实现此功能。


看一下这个链接:https://dev59.com/fm445IYBdhLWcg3wiq8i#26865122,我认为它可以解决你的问题。 - Alex GS
3个回答

16

您可以使用Comparator通过流来排序数据。

//first comparison
Comparator<YourType> comparator = Comparator.comparing(s -> s.intervalType.orderIndex);

//second comparison
comparator = comparator.thenComparing(Comparator.comparing(s-> s.item.amount));

//sorting using stream
result.stream().sorted(comparator).collect(Collectors.toList())

2

我已经找到了最好的方法来实现它,因为我正在使用Kotlin,所以可以这样做:

result.sortedWith(compareBy({ it.intervalType.orderIndex }, { it.item.amount }))

0

如果您正在使用Kotlin - 您应该按Kotlin的方式进行操作。

拥有内部

class Internal(val orderIndex: Int, val ammount: Int)

你可以轻松地使用compareBy编写任意组合的比较器。

// result: List<Internal>
result.sortedWith(compareBy( {it.orderIndex}, {it.ammount} ))

在你的任务中不需要使用流,你可以直接完成。 如果你确实需要使用流 - 在流内使用这个compareBy聚合函数:
result.stream().sorted(compareBy( ... ).collect( ... )

这就是我在之前评论中写的。 - Sahbaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接