Convert Set> to HashMap

后端 未结 6 1351
礼貌的吻别
礼貌的吻别 2020-12-03 02:25

At one point in my code, I created a Set> from a map. Now I want to recreate the same map form, so I want to convert the HashS

6条回答
  •  余生分开走
    2020-12-03 03:22

    Fairly short Java 8 solution. Can cope with duplicate keys.

        Map map = new HashMap<>();
        //fill in map
        Set> set = map.entrySet();
        Map mapFromSet = set.stream().collect(Collectors.toMap(Entry::getKey,
          Entry::getValue,
          (a,b)->b));
    

    Edit: thanks to shmosel who deserves more credit than I do for this

提交回复
热议问题