我需要对一个有大约 100 个键值对的映射进行排序,如“H”:“Hector”、“A”:“Alpha”等,我需要按特定顺序对前 10 个键值对进行排序

I need to sort a map which have around 100 key value pairs as "H":"Hector", "A":"Alpha" and so on, I need to sort first 10 in a specific order

提问人:Vivek Pandey 提问时间:11/8/2023 更新时间:11/17/2023 访问量:33

问:


Map<String, String> records = new HashMap<>();
        HOSTING.put("H", "Hector");
        HOSTING.put("B", "Bravo");
        HOSTING.put("W", "Whiskey");
        HOSTING.put("P", "Papa");


Map<String, String> finalMap = records .entrySet().stream().filter(x-> {
            if(x.getKey().equals("W") || x.getKey().equals("B")){
                return true;
            }
                return false;
        }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println("finalMap"+finalMap);

我需要“W”和“B”前 2 个条目,然后全部休息,我尝试过滤,但这只剩下 W 和 B 的值,相反,我试图让所有条目都成为我选择的前 2 个条目。

请帮忙。

排序 过滤器 集合 java-8 java-stream

评论

1赞 Holger 11/9/2023
我想,并且注定是同一张地图?recordsHOSTING

答:

1赞 Holger 11/9/2023 #1

如果要获得排序结果,则必须使用 ,而不是 .但是,您还需要收集到将保留顺序的地图中:sortedfilter

Map<String, String> records = new HashMap<>();
records.put("H", "Hector");
records.put("B", "Bravo");
records.put("W", "Whiskey");
records.put("P", "Papa");

Map<String, String> finalMap = records.entrySet().stream()
    .sorted(Comparator.comparing(
        x -> !(x.getKey().equals("W") || x.getKey().equals("B"))))
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a,b) -> { throw new AssertionError("keys should be unique already"); },
        LinkedHashMap::new));
System.out.println("finalMap"+finalMap);

在这里,您可以轻松扩展要放置在开头的元素集。

请注意,我们必须否定条件,因为 的自然顺序是 , 。Booleanfalsetrue

但是,由于您的问题的标题显示“前 10 名”,您可能想要更具可扩展性的东西:

Set<String> toTheTop = Set.of("B", "W");
Map<String, String> finalMap = records.entrySet().stream()
    .sorted(Comparator.comparing(x -> !(toTheTop.contains(x.getKey()))))
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a,b) -> { throw new AssertionError("keys should be unique already"); },
        LinkedHashMap::new));

在这里,您可以轻松展开要放置在开头的键集。

顺便说一句,不要写类似
You can simply write 或者在 lambda 表达式的情况下,只需 .
if(condition) return true; [else] return false;return condition;parameter -> condition

评论

0赞 Vivek Pandey 11/9/2023
感谢您的帮助,工作就像一个魅力。
1赞 Holger 11/9/2023
然后你可以接受答案。
1赞 Jean-Baptiste Yunès 11/17/2023 #2

使用 a 对键进行排序。您可以控制密钥顺序:TreeMap

Comparator<String> c = (s1,s2) -> {
      int c1 = s1.charAt(0);
      int c2 = s2.charAt(0);
      // H will be the first of all
      if (c1=='H') return -1;
      if (c2=='H') return 1;
      // W the second
      if (c1=='W') return -1;
      if (c2=='W') return 1;
      // Others in alphabetic order.
      return c1-c2;
    };
    Map<String, String> records = new TreeMap<>(c);
    records.put("H", "Hector");
    records.put("B", "Bravo");
    records.put("W", "Whiskey");
    records.put("P", "Papa");    
    System.out.println("finalMap"+records);