1. Overview
1.概述
In our previous tutorial, A Guide to Java HashMap, we showed how to use HashMap in Java.
在我们之前的教程中,Java HashMap指南,我们展示了如何在Java中使用HashMap。
In this short tutorial, we’ll learn how to get a submap from a HashMap based on a list of keys.
在这个简短的教程中,我们将学习如何从一个HashMap中获得一个基于键列表的子图。
2. Use Java 8 Stream
2.使用Java 8流
For example, suppose we have a HashMap and a list of keys:
例如,假设我们有一个HashMap和一个键的列表。
Map<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
map.put(4, "D");
map.put(5, "E");
List<Integer> keyList = Arrays.asList(1, 2, 3);
We can use Java 8 streams to get a submap based on keyList:
我们可以使用Java 8流来获得基于keyList的子图。
Map<Integer, String> subMap = map.entrySet().stream()
.filter(x -> keyList.contains(x.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(subMap);
The output will look like this:
输出将看起来像这样。
{1=A, 2=B, 3=C}
3. Use retainAll() Method
3.使用retainAll()方法
We can get the map’s keySet and use the retainAll() method to remove all entries whose key is not in keyList:
我们可以获得地图的keySet,并使用retainAll()方法来删除所有键值不在keyList中的条目。
map.keySet().retainAll(keyList);
Note that this method will edit the original map. If we don’t want to affect the original map, we can create a new map first using a copy constructor of HashMap:
注意,这个方法将编辑原始地图。如果我们不想影响原始地图,我们可以先用HashMap的复制构造函数创建一个新的地图。
Map<Integer, String> newMap = new HashMap<>(map);
newMap.keySet().retainAll(keyList);
System.out.println(newMap);
The output is the same as above.
其输出结果与上述相同。
4. Conclusion
4.总结
In summary, we’ve learned two methods to get a submap from a HashMap based on a list of keys.
综上所述,我们已经学会了两种方法来从HashMap中获得一个基于键列表的子图。