还原键/值地图

时间:2016-06-15 19:05:58

标签: java-8

我们说我有一个String of List / List

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);

      }

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我会使用guava的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);

Multimap将包含反向映射。如果要将结果放在java.util.Map对象中,请使用Multimap.asMap()