返回按升序排序的结果java

返回按升序排序的结果java

本文介绍了Collectors.groupingBy()返回按升序排序的结果java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按降序发送结果但是我按升序输出

I am sending result in descending order but I get output with ascending order

List<myEntity> myData = new ArrayList<>();
Map<Integer,List<myEntity>> myid = new LinkedHashMap<>();

try {
    myData = myService.getData(id);
    myid = myData.stream().collect(Collectors.groupingBy(myEntity::getDataId));

这里mydata按desc顺序排序,但按组数据ID创建集合后,我的列表按升序排序订购。我希望我的收藏列表是降序而不是升序。

Here mydata is sorted by desc order but after creating collections by group data id my list get sorted with ascending order. I want my collection list to be descending order not ascending order.

推荐答案

正如@Hrefger中描述的
,Collectors.groupingBy ()返回一个HashMap,它不保证顺序。

As @Holger described in Java 8 is not maintaining the order while grouping, Collectors.groupingBy() returns a HashMap, which does not guarantee order.

以下是您可以做的事情:

Here is what you can do:

myid = myData.stream()
.collect(Collectors.groupingBy(MyEntity::getDataId,LinkedHashMap::new, toList()));

将返回 LinkedHashMap<整数,列表< MyEntity>> 。订单也将保留,因为收集器使用的列表是ArrayList。

Would return a LinkedHashMap<Integer, List<MyEntity>>. The order will also be maintained as the list used by collector is ArrayList.

这篇关于Collectors.groupingBy()返回按升序排序的结果java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:34