Map implementation with duplicate keys

后端 未结 18 1912
暗喜
暗喜 2020-11-22 15:23

I want to have a map with duplicate keys.

I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know

18条回答
  •  一生所求
    2020-11-22 15:55

    No fancy libs required. Maps are defined by a unique key, so dont bend them, use a list. Streams are mighty.

    import java.util.AbstractMap.SimpleImmutableEntry;
    
    List> nameToLocationMap = Arrays.asList(
        new SimpleImmutableEntry<>("A", "A1"),
        new SimpleImmutableEntry<>("A", "A2"),
        new SimpleImmutableEntry<>("B", "B1"),
        new SimpleImmutableEntry<>("B", "B1"),
    );
    

    And thats it. Usage examples:

    List allBsLocations = nameToLocationMap.stream()
            .filter(x -> x.getKey().equals("B"))
            .map(x -> x.getValue())
            .collect(Collectors.toList());
    
    nameToLocationMap.stream().forEach(x -> 
    do stuff with: x.getKey()...x.getValue()...
    

提交回复
热议问题