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

问题描述 投票:0回答:1

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”前两个条目,然后其余所有,我尝试过滤,但这只留下了 W 和 B 的值,相反,我试图拥有所有条目,但前两个条目是我的选择。

请帮忙。

sorting filter collections java-8 java-stream
1个回答
0
投票

如果你想得到排序结果,你必须使用

sorted
,而不是
filter
。但是,您还需要收集到保留顺序的地图中:

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);

请注意,我们必须否定该条件,因为

Boolean
的自然顺序是
false
true

但是由于你的问题的标题说“前 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));

作为旁注,不要写类似

if(condition) return true; [else] return false;

的内容 您可以简单地写
return condition;
或者在 lambda 表达式的情况下,只需写
parameter -> condition

© www.soinside.com 2019 - 2024. All rights reserved.