有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据列表中的元素对映射中的键进行排序

我希望根据列表中可用的键(列表中元素的顺序是不可变的)在地图中排列/排序元素,这样使用java时,地图和列表中的键的顺序应该相同

地图中的数据:

{grocery=150, utility=130, miscellneous=90, rent=1150,
 clothes=120, transportation=100}

列表中的数据:

[utility, miscellneous, clothes, transportation, rent]

预期结果:

{utility=130, miscellneous=90, clothes=120, transportation=100, rent=1150 }

共 (3) 个答案

  1. # 1 楼答案

    您必须遍历所需的键列表,并从Map中检索值。为了维持秩序,你应该使用LinkedHashMap

    public static Map<String, Integer> sort(Map<String, Integer> map, String[] keys) {
        return Arrays.stream(keys).collect(Collectors.toMap(key -> key, map::get, Integer::sum, LinkedHashMap::new));
    }
    
  2. # 2 楼答案

    这不是一种。 您希望从列表开始处理元素
    假设文本值为字符串,数值为整数,可以这样做:

    Map<String, Integer> finalMap = 
    list.stream()
        .collect(toMap(o->o, map.get(o), (a,b)->a, LinkedHashMap::new));
    

    还是:

    LinkedHashMap<String, Integer> finalMap = new LinkedHashMap<>();
    list.forEach(o-> finalMap.put(o, map.get(o));
    
  3. # 3 楼答案

    您可以使用Comparator根据给定列表中映射的的出现索引对映射进行排序,然后为了保留排序顺序,将其收集到LinkedHashMap

    public static void main(String[] args) throws Exception {
            Map<String, Integer> map = new HashMap<>();
            map.put("grocery", 150);
            map.put("utility", 130);
            map.put("miscellneous", 90);
            map.put("rent", 1150);
            map.put("clothes", 120);
            map.put("transportation", 100);
    
            List<String> list = new ArrayList<>(
                                Arrays.asList("utility", "miscellneous", "clothes", 
                                              "transportation", "rent"));
            Map<String, Integer> sortedMap 
            = map.keySet()
                 .stream()
                 .filter(list::contains)
                 .sorted(Comparator.comparing(list::indexOf))
                 .collect(LinkedHashMap::new, 
                         (linkMap, key) -> linkMap.put(key, map.get(key)), 
                         Map::putAll);
    
            System.out.println(sortedMap);
     }
    

    输出:

     {utility=130, miscellneous=90, clothes=120, transportation=100, rent=1150}