'How to add HashMap values into an ArrayList

I have a HashMap and I am iterating like this:

for(HashMap<String, Integer> aString : value){
                System.out.println("key : " + key + " value : " + aString);

            }

I get the result as:

key : My Name value : {SKI=7, COR=13, IN=30}

Now I need to separate the `SKI , COR and IN into 3 different ArrayLists with their corresponding values? How to do that?



Solution 1:[1]

If your data is always JSON, you can simply decode it as you normally would using JSON:

ArrayList<Integer> array = new ArrayList<Integer>();
JSONArray json = new JSONArray(aString);
for (int i =0; i< json.length(); i++) {
    array.add(json.getInt(i));
}

Solution 2:[2]

I'm not super sure what your hashmap contains because your code is so brief, but it almost looks like it is giving you the toString() of the hashmap. The best way to iterate through a hashmap would be:

    Map mp;
    .....
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        String key = pairs.getKey();
        String value = pairs.getValue();
        //Do something with the key/value pair
    }

But if you are iterating through your hashmap correctly then below is the solution to manually parse that string into three different arraylists, this is probably the safest way to do it.

ArrayList < String > ski = new ArrayList < String > ();
ArrayList < String > cor = new ArrayList < String > ();
ArrayList < String > in = new ArrayList < String > ();

for (HashMap < String, Integer > aString: value) {
    System.out.println("key : " + key + " value : " + aString);
    aString.replace("{", "");
    aString.replace("}", "");
    String[] items = aString.split(", ");
    for (String str: items) {
        if (str.contains("SKI")) {
            String skiPart = str.split("=");
            if (skiPart.length == 2) ski.add(skiPart[1]);
        }
        elseif(str.contains("COR")) {
            String corPart = str.split("=");
            if (corPart.length == 2) cor.add(corPart[1]);
        }
        elseif(str.contains("IN")) {
            String inPart = str.split("=");
            if (inPart.length == 2) in.add(inPart[1]);
        }
    }

}

Solution 3:[3]

Here is an ArrayList (or List) full of HashMaps:

ArrayList<HashMap<String, Object>> userNotifications = new ArrayList<HashMap<String, Object>>();
int count = 0;

HashMap<String, Object> notificationItem = new HashMap<String, Object>();
notificationItem.put("key1", "value1");
notificationItem.put("key2", "value2");
userNotifications.add(count, notificationItem);
count++;

Then to retrieve the values:

ArrayList<HashMap<String, Object>> resultGetLast5PushNotificationsByUser = new ArrayList<HashMap<String, Object>>();

resultGetLast5PushNotificationsByUser = methodThatReturnsAnArrayList();
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(0);
String value1= item1.get("key1");
String value2= item1.get("key2");
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(1);
String value1= item1.get("key1");
String value2= item1.get("key2");

Solution 4:[4]

It is not clear what is the shape of your expected output.

Three lists like this:

[7]
[13]
[30]

or a mapping from keys to three lists like this:

{ "SKI" -> [7]  }
{ "COR" -> [13] }
{ "IN"  -> [7]  }

?

Nevertheless, here are some options:

Option 1

// HashMap does not preserve order of entries
HashMap<String, Integer> map = new HashMap<>();
map.put("SKI", 7);
map.put("COR", 13);
map.put("IN", 30);

List<List<Integer>> listOfLists = map.values()
                                     .stream()
                                     .map(Collections::singletonList)
                                     .collect(Collectors.toList());

listOfLists.forEach(System.out::println);
Output:
[7]
[30]
[13]

Option 2

// LinkedHashMap preserves order of entries
LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
map2.put("SKI", 7);
map2.put("COR", 13);
map2.put("IN", 30);

List<List<Integer>> listOfLists2 = map2.values()
                                       .stream()
                                       .map(Collections::singletonList)
                                       .collect(Collectors.toList());

listOfLists2.forEach(System.out::println);
Output:
[7]
[13]
[30]

Option 3

HashMap<String, Integer> map3 = new HashMap<>();
map3.put("SKI", 7);
map3.put("COR", 13);
map3.put("IN", 30);

HashMap<String, List<Integer>> result = new HashMap<>();
map3.forEach((key, value) -> result.put(key, Collections.singletonList(value)));

result.entrySet().forEach(System.out::println);
Output:
SKI=[7]
IN=[30]
COR=[13]

Option 4

Map<String, List<Integer>> result =
        map4.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    // key mapping
                    entry -> entry.getKey(),
                    // value mapping
                    entry -> Collections.singletonList(entry.getValue())
                    )
            );

result.forEach((key, val) -> System.out.println(key + " " + val));
Output:
SKI [7]
IN [30]
COR [13]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Lammertsma
Solution 2 knennigtri
Solution 3
Solution 4