Vargars in Java Hashmap

HashMap <String,String... strings> hm = new HashMap<String,String... strings>();

hm.put("Zara", "Pony","Cars", "Magic");
hm.put("John", "Horse","Flying", "Loving");

I want to do this, how do I do this? This does not allow me.

+4
source share
5 answers

The elipsis ( ...) operator can only be used in method signatures. You can explicitly declare and create arrays:

Map<String, String[]> hm = new HashMap<>();

hm.put("Zara", new String[]{"Pony", "Cars", "Magic"});
hm.put("John", new String[]{"Horse", "Flying", "Loving"});

If you absolutely must use varags, you can bind a call to Map#putyour method:

public static void main(String[] args) {
    Map<String, String[]> hm = new HashMap<>();

    addToMap(hm, "Zara", "Pony", "Cars", "Magic");
    addToMap(hm, "John", "Horse", "Flying", "Loving");
}

private static void addToMap
    (Map<String, String[]> map, String key, String... values) {
    map.put(key, values);
}
+3
source

Closest you can use the "Map" and create a method for this

public static void addToMap(Map<String, String[]> map, String key, String...values) {
    map.put(key, values);
}
+1
source

Vararg , . .

, . varargs . List Set.

:

  • :

    HashMap <String, String[]> hm = new HashMap<>();
    hm.put("Zara", new String[] {"Pony","Cars", "Magic"});
    hm.put("John", new String[] {"Horse", "Flying", "Loving"});
    
  • :

    HashMap <String, List<String>> hm = new HashMap<>();
    hm.put("Zara", new ArrayList<String>());
    hm.get("Zara").add("Pony");
    hm.get("Zara").add("Cars");
    hm.get("Zara").add("Magic");
    hm.put("John", new ArrayList<String>());
    hm.get("John").add("Horse");
    hm.get("John").add("Flying");
    hm.get("John").add("Loving");
    
+1
source

See this question . Basically you need to do the following:

hm.put("Zara", new String[]{"Pony", "Cars", "Magic"});

Or if you want to declare it separately:

String[] zaraValues = new String[]{"Pony", "Cars", "Magic"};
hm.put("Zara", zaraValues);
0
source

You may be looking for the following:

HashMap<String, List<String>> hm = new HashMap<>();
hm.put("Zara", Arrays.asList("Pony", "Cars", "Magic"));
hm.put("John", Arrays.asList("Horse", "Flying", "Loving"));
0
source

Source: https://habr.com/ru/post/1695506/


All Articles