让我们说我有一张字符串/列表
Map<String, List<String>> map = new HashMap<>();
map.put("product1", Arrays.asList("res1", "res2"));
map.put("product2", Arrays.asList("res1", "res2"));
键是字母,值是"数字"
的列表现在,我要实现的目标是在地图上迭代,并将"数字"的地图作为键,而"字母"作为价值。像
<"res1", List<"product1","product2" >>
<"res2", List<"product1","product2" >>
目前我设法做到了,但是分为两个步骤,并且代码看起来很词
@Test
public void test2() throws InterruptedException {
List<String> restrictions = Arrays.asList("res1", "res2");
Map<String, List<String>> productsRes = new HashMap<>();
productsRes.put("product1", restrictions);
productsRes.put("product2", restrictions);
ArrayListMultimap multiMap = productsRes.keySet()
.stream()
.flatMap(productId -> productsRes.get(productId)
.stream()
.map(restriction -> {
Multimap<String, List<String>> multimap = ArrayListMultimap.create();
multimap.put(restriction, Arrays.asList(productId));
return multimap;
}))
.collect(ArrayListMultimap::create, (map, restriction) -> map.putAll(restriction),
ArrayListMultimap::putAll);
Map<String, List<String>> resProducts = Multimaps.asMap(multiMap);
}
有任何建议吗?
谢谢!
我将使用番石榴的多件图,然后收集结果:
// the input map
Map<String, List<String>> lettersNumbers = new HashMap<>();
lettersNumbers.put("a", Arrays.asList("1", "2"));
// the output multimap
Multimap<String, String> result =
lettersNumbers.entrySet()
.stream()
.collect(ArrayListMultimap::create,
(map, entry) -> {
entry.getValue().forEach((val) ->
map.put(val, entry.getKey()));
},
ArrayListMultimap::putAll);
该多件将包含反向映射。如果要在Java.util.map对象中进行结果,请使用Multimap.asMap()
。