Let's consider that we have a HashMap
of the following type:
Map<String, List<String>> myMap = new HashMap<>();
We want to iterate through the entire hashmap and get all the values to a single List<String>
. There could be many ways to solve this problem in Java but let's take a look at a couple of simpler ways.
The first way is to use the values
method:
List<String> myList = new ArrayList<>(map.values());
Since most of us are already using JDK >=8 we can also use the following but that's a little more verbose :)
:
List<String> myList = map.values().stream().collect(Collectors.toList());