salmaan
salmaan

Reputation: 13

Add multiple values to map using same key?

This is what I have so far

Map<String, String> courses = new HashMap();
courses.put("Teachers","adam");

so how do I add more teachers using the same key

Upvotes: 0

Views: 77

Answers (3)

TongChen
TongChen

Reputation: 1430

if you can use google guava,Interface Multimap<K,V> is a good way to do this,and all opereation is simple。

To add a dependency on Guava using Maven, use the following:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>27.0.1-jre</version>
  <!-- or, for Android: -->
  <version>27.0.1-android</version>
</dependency>

Upvotes: 0

Squirrely Wrath
Squirrely Wrath

Reputation: 36

You can use Map<String, ArrayList<String>>. Then add additional information by doing map.get("Teachers").add("Bob")

Upvotes: 2

khachik
khachik

Reputation: 28703

You can benefit from computeIfAbsent:

Map<String, List<String>> courses = new HashMap<>();
courses.computeIfAbsent("Teachers", k -> new ArrayList<>()).add("adam");

Upvotes: 0

Related Questions