adding a key to HashMap without the value?

前端 未结 5 2255
孤城傲影
孤城傲影 2021-02-19 14:37

Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a HashMap> amd I wan

5条回答
  •  余生分开走
    2021-02-19 14:49

    Since you're using a Map>, you're really looking for a multimap. I highly recommend using a third-party library such as Google Guava for this - see Guava's Multimaps.

    Multimap myMultimap = ArrayListMultimap.create();
    
    // fill it
    myMultimap.put("hello", "hola");
    myMultimap.put("hello", "buongiorno");
    myMultimap.put("hello", "สวัสดี");
    
    // retrieve
    List greetings = myMultimap.get("hello");
                          // ["hola", "buongiorno", "สวัสดี"]
    

    Java 8 update: I'm no longer convinced that every Map> should be rewritten as a multimap. These days it's quite easy to get what you need without Guava, thanks to Map#computeIfAbsent().

    Map> myMap = new HashMap<>();
    
    // fill it
    myMap.computeIfAbsent("hello", ignored -> new ArrayList<>())
      .addAll(Arrays.asList("hola", "buongiorno", "สวัสดี");
    
    // retrieve
    List greetings = myMap.get("hello");
                          // ["hola", "buongiorno", "สวัสดี"]
    

提交回复
热议问题