2

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2
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

where does innerMap come from? there is no variable that contain value of inner map isn't it?
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.
0

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()));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.