java 8 List<Map<String,String>>转 Map<String,String>

古月三水
  • 5
新手上路,请多包涵
    List<Map<String, String>> listMap = new ArrayList<>();
    Map<String, String> map1 = new HashMap<>();
    Map<String, String> map2 = new HashMap<>();
    Map<String, String> map3 = new HashMap<>();
    listMap.add(map1);
    listMap.add(map2);
    listMap.add(map3);
    map1.put("name","yuwen");
    map1.put("code","01");
    map2.put("name","shuxu");
    map2.put("code","02");
    map3.put("name","yingyu");
    map3.put("code","03");

    System.out.println(listMap.toString());
    //[{code=01, name=yuwen}, {code=02, name=shuxu}, {code=03, name=yingyu}]

    //期望转为
    Map<String, String> map = new HashMap<>();
    map.put("yuwen","01");
    map.put("shuxu","02");
    map.put("yingyu","03");

    System.out.println(map.toString());
    //{yingyu=03, yuwen=01, shuxu=02}
回复
阅读 413
3 个回答
        Map<String, String> collect = listMap.stream().collect(
                Collectors.toMap(
                        t -> t.get("name"),
                        t -> t.get("code"),
                        (o, n) -> n,
                        HashMap::new
                )
        );
List<Map<String, String>> listMap = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        Map<String, String> map2 = new HashMap<>();
        Map<String, String> map3 = new HashMap<>();
        listMap.add(map1);
        listMap.add(map2);
        listMap.add(map3);
        map1.put("name", "yuwen");
        map1.put("code", "01");
        map2.put("name", "shuxu");
        map2.put("code", "02");
        map3.put("name", "yingyu");
        map3.put("code", "03");

        System.out.println(listMap.toString());
        //[{code=01, name=yuwen}, {code=02, name=shuxu}, {code=03, name=yingyu}]
        HashMap<String, String> collect = listMap.stream().reduce(new HashMap<>(), (m1, m2) -> {
            m1.put(m2.get("name"), m2.get("code"));
            return m1;
        }, (m1, m2) -> m1);

        System.out.println(collect);

使用 Collectors.toMap

Map<String, String> expectedMap 
        = listMap.stream().collect(Collectors.toMap(m -> m.get("name"), m -> m.get("code")));
你知道吗?

宣传栏