【问题标题】:Revert key/value Map [duplicate]还原键/值映射 [重复]
【发布时间】: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


    【解决方案1】:

    我会使用番石榴中的 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()

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-12
    • 2017-05-19
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多