我想要一个具有重复键的映射。
我知道有很多map实现(Eclipse向我展示了大约50个),所以我打赌肯定有一个允许这样做。我知道编写自己的地图很容易做到这一点,但我更愿意使用一些现有的解决方案。
也许是commons-collections或google-collections中的一些东西?
发布于 2019-11-19 22:08:27
不需要花哨的库。映射是由一个唯一的键定义的,所以不要弯曲它们,使用列表。小溪是强大的。
import java.util.AbstractMap.SimpleImmutableEntry;
List<SimpleImmutableEntry<String, String>> nameToLocationMap = Arrays.asList(
new SimpleImmutableEntry<>("A", "A1"),
new SimpleImmutableEntry<>("A", "A2"),
new SimpleImmutableEntry<>("B", "B1"),
new SimpleImmutableEntry<>("B", "B1"),
);就是这样。使用示例:
List<String> 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()...https://stackoverflow.com/questions/1062960
复制相似问题