how to add multiple values to single key in java

Viewed 18715

How can I create a map that can extend its list of value. For example I have a map which contains: key A and list of values B {1,2,3}. Then at some point during the program running, I would like to add more value, ex: 4 to list B. Now my new map should be something like: (A,{1,2,3,4}). How can I do that?

6 Answers
 public static void main(String[] args) {

Map<String, List<String>> map = new HashMap<String, List<String>>();

List<String> valSetOne = new ArrayList<String>();
valSetOne.add("ABC");
valSetOne.add("BCD");
valSetOne.add("DEF");

List<String> valSetTwo = new ArrayList<String>();
valSetTwo.add("CBA");
valSetTwo.add("DCB");

map.put("FirstKey", valSetOne);
map.put("SecondKey", valSetTwo);

for (Map.Entry<String, List<String>> entry : map.entrySet()) {

    String key = entry.getKey();

    List<String> values = entry.getValue();

    System.out.println("Value of " + key + " is " + values);

}

}

You can use Set or List based on your requirement.This is a simple method of having single key with multiple values.

Java 8. Stream API.

For example we have collection of Users as List:

[{ name: "qwer", surname: "asdf", type: "premium"}, { name: "ioup", surname: "vmnv", type: "usual"}, { name: "rtyr", surname: "zxc", type: "premium"}] 

and we need to add multiple Users to Map where key is «type»

Map<String, List<User>> map = collection.stream().collect(Collectors.groupingBy(User::getType, Collectors.mapping(Function.identity(), Collectors.toList())))

To process this map we can make new stream

map.entrySet().stream().{map|reduce|& other things}...
Related