I want to build up a map based on 2 arrays where 1 key has many objects inside it.
Key: "Letter A" Value: "Albatross" Value: "Alligator"
Key: "Letter B" Value: "Badger" Value: "Bandicoot"
The structure must show the key 1 time, without repetitions
CodePudding user response:
Hope the code is self explanatory.
Java 7:
public Map<String, List<String>> group(String[] input) {
Map<String, List<String>> result = new HashMap<>();
for (String str : input) {
String key = "Letter " str.charAt(0);
if (result.containsKey(key)) {
result.get(key).add(str);//if Key already exists, just add this word to existing list.
} else {
List<String> list = new ArrayList<>();
list.add(str);
result.put(key, list); //Otherwise, create a new list and add the new word into the list
}
}
return result;
}
Java 8:
public static Map<String, List<String>> group(String[] input) {
return Arrays.stream(input)
.collect(Collectors.groupingBy(k -> "Letter " k.charAt(0)));
//Provide the key for how you want to group. In your case it is first character of string.
}
CodePudding user response:
You can use Guava's Mutlimap implementation, however that may not be Java 7 compatible. https://guava.dev/releases/23.0/api/docs/com/google/common/collect/Multimap.html
You can get the same effect by using a List for the values in your map like so:
Map<String, List<String>> map = new HashMap<>();
Then, let's say for each entry you want to add to the map you have the key in key
and value in val
, add it like so:
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(val);