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"
};
- stream the string array using Arrays.stream
- Use String.split to split each string on the
_
to create an array ofs[]
of the two elements - use Collectors.groupingBy to group based on a key, in this case,
s[0]
- then use Collectors.mapping to map to
s[1]
and put in a list.
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;
}