简体   繁体   English

根据两个值对地图列表进行排序

[英]Sort a list of maps based on two values

Here is the initialization code:下面是初始化代码:

List<Map<String, Object>> list = new ArrayList<>();

Map<String, Object> map1 = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
Map<String, Object> map3 = new HashMap<>();
Map<String, Object> map4 = new HashMap<>();
Map<String, Object> map5 = new HashMap<>();

map1.put("Age", 23);
map2.put("Age", 24);
map3.put("Age", 25);
map4.put("Age", 23);
map5.put("Age", 24);

map1.put("Name", "Rohan");
map2.put("Name", "Shyam");
map3.put("Name", "George");
map4.put("Name", "Ram");
map5.put("Name", "Sam");

list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);

Now, I want to sort the list based on the 'Age' value, and then for each same 'Age' values, sort again based on the 'Name' value.现在,我想根据“年龄”值对列表进行排序,然后对于每个相同的“年龄”值,根据“姓名”值再次排序。

So, my required output is:所以,我需要的 output 是:

{Age=23, Name=Ram}

{Age=23, Name=Rohan}

{Age=24, Name=Sam}

{Age=24, Name=Shyam}

{Age=25, Name=George}

I am able to do the first sorting, but not able to perform the second one.我能够进行第一次排序,但无法执行第二次排序。

You could implement a custom Comparator based on those two values:您可以根据这两个值实现自定义Comparator器:

list.sort(Comparator.comparing((Map<String, Object> map) -> (Integer) map.get("Age"))
                    .thenComparing((Map<String, Object> map) -> (String) map.get("Name"))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM