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 的值,相反,我试图拥有所有条目,但前两个条目是我的选择。
请帮忙。
如果你想得到排序结果,你必须使用
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
。