Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Get a Submap From a HashMap in Java

$
0
0

1. Overview

In our previous tutorial, A Guide to Java HashMap, we showed how to use HashMap in Java.

In this short tutorial, we'll learn how to get a submap from a HashMap based on a list of keys.

2. Use Java 8 Stream

For example, suppose we have a HashMap and a list of keys:

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:

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:

{1=A, 2=B, 3=C}

3. Use retainAll() Method

We can get the map's keySet and use the retainAll() method to remove all entries whose key is not in 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:

Map<Integer, String> newMap = new HashMap<>(map);
newMap.keySet().retainAll(keyList);
System.out.println(newMap);

The output is the same as above.

4. Conclusion

In summary, we've learned two methods to get a submap from a HashMap based on a list of keys.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>