繁体   English   中英

在java中按键值对对地图列表进行排序

[英]Sort the list of maps by key Value pair in java

我有一个 JSON 文档。 我已将文档转换为 Map<String, String>,其中一些键将 Maps (List<Map<String,String>>) 列表作为值。 我想对这个 List<Map<String,String> 进行排序。

只是一个例子:(在将 JSON 文档存储在 Map<String,String>

1. key: name, value: {first=John, last=Doe}
2. key: address, value: null
3. key: birthday, value: 1980-01-01
4. key: company, value: Acme
5. key: occupation, value: Software engineer
6. key: phones, value: [{number=9, type=mobile1}, {number=1, type=mobile}, {type=home, number=0}]
7. key: groups, value: [gym, close-friends]

在上面的示例中,第 6 行Key = "phones" 具有作为我必须排序的地图列表的值。

预期输出:

1. key: name, value: {first=John, last=Doe}
2. key: address, value: null
3. key: birthday, value: 1980-01-01
4. key: company, value: Acme
5. key: occupation, value: Software engineer
6. key: phones, value: [{number=0, type=home}, {number=1, type=mobile}, {number=9, type=mobile1}]
7. key: groups, value: [gym, close-friends]

我想对这个 List<Map<String,String> 进行排序。

鉴于您显示的数据,所有地图都只有一个条目。 所以我们按这个条目的键排序。 特别是通过它们的integer数值。

List<Map<String, String>> myMapList 
      = // get list of maps here
    Collections.sort(myMapList, new Comparator<Map<String, String>>() {
        @Override
        public int compare(
          Map<String, String> m1, Entry<String, String> m2) {
            var key1 = m1.keySet().iterator().next();
            var key2 = m2.keySet().iterator().next()
            return Integer.valueOf(key1).compareTo(Integer.valueOf(key2));
        }
    });

有关更多详细信息,请查看此内容

这能解决您的问题吗? 在评论中告诉我。

你可以使用列表。 排序()

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Main {
    private static final String TYPE = "type";
    private static final String NUMBER = "number";

    public static void main(String[] args) {
        Map<String, List<Map<String, String>>> jsonMap = new HashMap<>();
        jsonMap.put("phones", new ArrayList<>(Arrays.asList(
                                    Map.of(NUMBER, "9", TYPE, "mobile1"), 
                                    Map.of(NUMBER, "1", TYPE, "mobile"),
                                    Map.of(TYPE, "home", NUMBER, "0"))));
        
        System.out.println("Before:");
        System.out.println(jsonMap);

        jsonMap.get("phones").sort((a, b) -> 
            Integer.valueOf(a.get(NUMBER)).compareTo(Integer.valueOf(b.get(NUMBER))));

        System.out.println("After:");
        System.out.println(jsonMap);
    }

}

输出:

Before:
{phones=[{type=mobile1, number=9}, {type=mobile, number=1}, {type=home, number=0}]}
After:
{phones=[{type=home, number=0}, {type=mobile, number=1}, {type=mobile1, number=9}]}

暂无
暂无

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

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