How to Convert HashMap Keys/Values to Set in Java

Published Jun 5, 2022  ∙  Updated Jun 6, 2022

Suppose we have the following HashMap that we’d like to convert into a Set.

Map<String, Integer> map = new HashMap<>();

1. Convert HashMap keys to Set

We can convert all keys into a set using keySet().

Set<String> setOfKeys = map.keySet();

2. Convert HashMap values to Set

We can convert all values into a set using values().

Set<Integer> setOfValues = new HashSet<Integer>(map.values());