0

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

6
  • Then it should be Map<String, List<String>> courses Commented Feb 14, 2019 at 2:58
  • And new HashMap<>(). (Don't use raw types) Commented Feb 14, 2019 at 3:00
  • I am getting error if i use "List" Commented Feb 14, 2019 at 3:00
  • You will have to first make sure the "Teachers" key exists in courses map, then you have to do courses.get("Teachers").add("adam"). The only downside to using Map<String, List<String>> is that all keys have to be lists now, so you'll have to update all references to courses variable. Commented Feb 14, 2019 at 3:05
  • Post the error @salmaan Commented Feb 14, 2019 at 3:10

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

how do you add new key
map.put("Teachers", new ArrayList ());
map.get("Teachers") gives you an ArrayList, so you can access it's values using an index or .contains("Bob") or .indexOf("Bob")
0

You can benefit from computeIfAbsent:

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.