您好,欢迎访问代理记账网站
移动应用 微信公众号 联系我们

咨询热线 -

电话 15988168888

联系客服
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

java8使用stream把List转为Map,根据key提取值转List

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Test {

    public static void main(String[] args) {

        List<Map<String, String>> list = new ArrayList<>();

        {
            Map<String, String> map = new HashMap<>();
            map.put("id", "1");
            map.put("name", "B");
            map.put("age", "C");
            list.add(map);
        }

        {
            Map<String, String> map = new HashMap<>();
            map.put("id", "1");
            map.put("name", "E");
            map.put("age", "F");
            list.add(map);
        }

        //1.返回结果{"1","B"},{"2","E"}
//        Map<String, String> a = list.stream().collect(Collectors.toMap(l -> l.get("id"), l -> l.get("name")));

        //2.两种方法返回结果{"1":{"name":"B","id":"1","age":"C"},"2":{"name":"E","id":"2","age":"F"}}
//        Map<String, Map> b = list.stream().collect(Collectors.toMap(l -> l.get("id"), map -> map));
//        Map<String, Map> c = list.stream().collect(Collectors.toMap(l -> l.get("id"), Function.identity()));

        //3.重复key情况下处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
//        Map<String, Map> d = list.stream().collect(Collectors.toMap(l -> l.get("id"), Function.identity(), (key1, key2) -> key2));

        //4.重复key情况下指定返回数据类型处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
//        Map<String, Map> e = list.stream().collect(Collectors.toMap(l -> l.get("id"), Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));


        //5.list根据key合并并转map;返回结果{"1":[{"name":"B","id":"1","age":"C"},{"name":"E","id":"1","age":"F"}]}
//        Map<String, List<Map>> lableGbType = list.stream().collect(Collectors.groupingBy(l -> (String) l.get("id")));

        //6.根据key提取list中指定的值转List数组;返回结果["1","1"]
//        List<String> ids = list.stream().map(m -> (String) m.get("id")).collect(Collectors.toList());


        //7.数组去重并转list
      /*  String[] str = "1,1,2,3,4,5,".split(",");
        List<String> listNames = Arrays.stream(str).filter(name -> !isEmpty(name)).distinct().collect(Collectors.toList());*/

    }


}

分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进