【发布时间】:2016-06-15 19:05:57
【问题描述】:
假设我有一个字符串/列表的映射
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);
}
有什么建议吗?
谢谢!
【问题讨论】:
标签: java-8