Home > Enterprise >  Convert this String into hashmap
Convert this String into hashmap

Time:02-04

Let's say i have strings like this

"game_2times" "game_3times" "game_4times" "listy_bubenicek" "listy_peneznieso"

what i want is to create a hashmap

HashMap<String,ArrayList<String>>

and have the strings splited into array like structure =>

key : "game" values="2times,3times,4times"

I tried this

        for (String item: names) {
            for (int i = 0; i < names.length; i  ) {
                ArrayList<String> c = new ArrayList<>();
                if(names[i].contains("game")) {
                    c.add(item);
                }
                hashmap.put(item.split("_")[0],c);
            }
        }

CodePudding user response:

Here is one way using streams.

String[] strings = {
        "game_2times","game_3times","game_4times","listy_bubenicek",
        "listy_peneznieso"
};

Map<String, List<String>> result = Arrays.stream(strings)
        .map(str -> str.split("_"))
        .collect(Collectors.groupingBy(s -> s[0],
                Collectors.mapping(s -> s[1], Collectors.toList())));

result.entrySet().forEach(System.out::println);

prints

game=[2times, 3times, 4times]
listy=[bubenicek, peneznieso]

Here is another option sans streams.

  • create a map to hold the results
  • Iterate thru the array, splitting the string as before.
  • computeIfAbsent will use the supplied argument as a key if it isn't present and will create and return the value of the function, in this case, an ArrayList.
  • then this and subsequent references to that key will add the value to the list for that key.
Map<String, List<String>> result = new HashMap<>();
for(String str : strings) {
    String[] strArray = str.split("_");
    result.computeIfAbsent(strArray[0], v->new ArrayList<>()).add(strArray[1]);
}

CodePudding user response:

There are more elegant ways of doing this but I will show the simple to understand way:

    public static Map<String, List<String>> flatten(List<String> names) {
    final Map<String, List<String>> result = new HashMap<>();
    for (String item : names) {
        final String[] parts = item.split("_");
        if (result.containsKey(parts[0])) {
            result.get(parts[0]).add(parts[1]);
        } else {
            final ArrayList<String> c = new ArrayList<>();
            c.add(parts[1]);
            result.put(parts[0], c);
        }
    }
    return result;
}
  •  Tags:  
  • java
  • Related