Skip to main content

APIzation: Replication Package

[Q#16516107][A#16516670] How can I store HashMap<String, ArrayList<String>> inside a list?

https://stackoverflow.com/q/16516107

My hashmap stores the string as key and arraylist as the values. Now, I need to embed this into a list. That is, it will be of the following form: These are the declarations I have used: Can anyone help me which method and how to use in the list to proceed storing my map into it?

Answer

https://stackoverflow.com/a/16516670

Always try to use interface reference in Collection, this adds more flexibility. What is the problem with the below code? You can easily do it like the above.

APIzation

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.
package com.stackoverflow.api;

import java.util.List;
import java.util.Map;

public class Human16516670 {

  public static List<Map<String, List<String>>> storeInList(
    Map<String, List<String>> map1,
    List<Map<String, List<String>>> list
  ) {
    list.add(map1); // In this way you can add.

    return list;
  }
}

package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * How can I store HashMap<String, ArrayList<String>> inside a list?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/16516670">https://stackoverflow.com/a/16516670</a>
 */
public class APIzator16516670 {

  public static void storeHashmap(List<String> arraylist1)
    throws Exception {
    // This is the final list you need
    List<Map<String, List<String>>> list = new ArrayList<Map<String, List<String>>>();
    // This is one instance of the  map you want to store in the above list.
    Map<String, List<String>> map1 = new HashMap<String, List<String>>();
    map1.put("key1", arraylist1);
    // And so on...
    // In this way you can add.
    list.add(map1);
  }
}