How to create a Multimap from a Map>?

前端 未结 6 1267
难免孤独
难免孤独 2020-12-03 01:02

I didn\'t find such a multimap construction... When I want to do this, I iterate over the map, and populate the multimap. Is there an other way?

final Map<         


        
6条回答
  •  無奈伤痛
    2020-12-03 01:16

    Here is a useful generic version that I wrote for my StuffGuavaIsMissing class.

    /**
     * Creates a Guava multimap using the input map.
     */
    public static  Multimap createMultiMap(Map> input) {
      Multimap multimap = ArrayListMultimap.create();
      for (Map.Entry> entry : input.entrySet()) {
        multimap.putAll(entry.getKey(), entry.getValue());
      }
      return multimap;
    }
    

    And an immutable version:

    /**
     * Creates an Immutable Guava multimap using the input map.
     */
    public static  ImmutableMultimap createImmutableMultiMap(Map> input) {
      ImmutableMultimap.Builder builder = ImmutableMultimap.builder();
      for (Map.Entry> entry : input.entrySet()) {
        builder.putAll(entry.getKey(), entry.getValue());
      }
      return builder.build();
    }
    

提交回复
热议问题