I know convert HashMap into List can be done by List<String> list = new ArrayList<>(hashMap.values());, But how about HashMap of HashMap?
Like: HashMap<String, HashMap<String, String>>, how to convert it into ArrayList<ArrayList<String>>?
My idea so far is List<List<String>> list = new ArrayList(hashMap.values());, but how to convert inner HashMap into list with/without iterate it?
Add a comment
|
3 Answers
For non-java 8 you can use
1.) Fetch entry set from your hashMapOfMaps
2.) hashMapOfMaps.getValue() will retrun HashMap<String, String> and then .values() return the String values of inner map
for (Entry<String, HashMap<String, String>> entry: hashMapOfMaps.entrySet()) {
listOfLists.add(new ArrayList<String>(entry.getValue().values()));
} | |
inner-Map |
|
inner-Map's string values
Comments
map.values().stream() // a stream of Map<String, String>
.map(innerMap -> new ArrayList<>(innerMap.values()) // a stream of List<String>
.collect(Collectors.toList()); // List of List<String>
Of course, you lose all key information.
2 Comments
Newbie
where does
innerMap come from? there is no variable that contain value of inner map isn't it?john16384
innerMap -> new ArrayList<>(innerMap.values()) is a Lambda, you can give the variable in the definition any name, and you can use it in the function part. x -> new ArrayList<>(x.values()) would also have worked, but is less readable. However, it will depend on if Java 8 is available for you, it depends on which Android API version you are developing for.Since you want this on android you might not want to use Java 8 streams. Here for JDK 7
HashMap<String, HashMap<String, String>> mapOpfMap = new HashMap<>();
List<List<String>> listOfList = new ArrayList<>();
Iterator<Map.Entry<String, HashMap<String, String>>> it = mapOpfMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, HashMap<String, String>> value = it.next();
value.getKey(); // here is the key if you need it
listOfList.add(new ArrayList<>(value.getValue().values()));
}