java 8中 sorted分类排序
java 8中 sorted分类排序
1.需求: 先按照 channelWeight 进行 降序排列,如果 channelWeight 相同 再按照 score进行降序排列。 下面是实体:
@Data class P { Double channelWeight; Double score; String channelName; }
普通的sorted的用法就是:
List<P> list = new ArrayList<>(); P productItem1 = new P(); productItem1.setChannelWeight(0.1D); productItem1.setChannelName("1"); productItem1.setScore(0.9D); P productItem2 = new P(); productItem2.setChannelWeight(0.1D); productItem2.setChannelName("1"); productItem2.setScore(0.8D); P productItem3 = new P(); productItem3.setChannelWeight(0.2D); productItem3.setChannelName("2"); productItem3.setScore(0.7D); P productItem4 = new P(); productItem4.setChannelWeight(0.2D); productItem4.setChannelName("2"); productItem4.setScore(0.6D); list.add(productItem1); list.add(productItem2); list.add(productItem3); list.add(productItem4); //仅仅按照 ChannelWeight 进行倒排。 list.stream().sorted(Comparator.comparingDouble(P::getChannelWeight).reversed()).collect(Collectors.toList());
reversed()作用:有它就是从大到小排列,没有就是从小到大排列
2.实现我们 1 的需求:
List<P> listAfterSortedByCwThenSc = list.stream().sorted(Comparator.comparingDouble(P::getChannelWeight).thenComparingDouble(P::getScore).reversed()) .collect(Collectors.toList());
仅仅在 getScore 后面增加一个 reversed()方法就行。 ⚠️注意:如果在 getChannelWeight 增加 reversed()方法同时 也在 getScore 增加 reversed()的话会发生有趣的现象,你们可以去试一下。 (狗头)