Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created December 3, 2013 20:20
Show Gist options
  • Save sscovil/7776852 to your computer and use it in GitHub Desktop.
Save sscovil/7776852 to your computer and use it in GitHub Desktop.
/**
* List To HashMap
*
* Converts a list of key/value pairs (in the form of String arrays) to a HashMap with values merged based on key.
*
* For example, if given the following list of arrays:
*
* [0] => { [0] => "Project A", [1] => "Asset 1" },
* [1] => { [0] => "Project A", [1] => "Asset 2" },
* [2] => { [0] => "Project B", [1] => "Asset 3" }
*
* This method would return:
*
* [ "Project A" => { "Asset 1", "Asset 2" } ],
* [ "Project B" => { "Asset 3" }
*
* @param list List of key/value pairs to convert to a HashMap.
* @return HashMap with values merged into an ArrayList based on key.
*/
private HashMap<String, ArrayList<String>> listToHashMap(List<String[]> list) {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(list.size());
String key;
String value;
ArrayList<String> valueList;
for (String[] result : list) {
key = result[0];
value = result[1];
valueList = (map.containsKey(key)) ? map.get(key) : new ArrayList<String>();
valueList.add(value);
map.put(key, valueList);
}
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment