List转Map

一、List转换为Map?

示例:代码案例

复制代码
public class People (
	private Integer id;
	private String name;
	private Integer age
	private String address;
	//TODO 构造方法和get和set方法省略
)

final static List<People> peopleList = new ArrayList<People>();


 // 初始化集合数据

static {
   People p1 = new People(0001, "张三", 12, "江苏南京");
   People p2 = new People(0002, "李四", 14, "上海");
   People p3 = new People(0003, "王二", 11, "浙江台州");
   People p4 = new People(0004, "李五", 12, "河南郑州");

   peopleList.add(p1);
   peopleList.add(p2);
   peopleList.add(p3);
   peopleList.add(p4);
}

1.1、List转化为Map<Integer,String>

复制代码
Map<Integer, String> map = peopleList.stream().collect(Collectors.toMap
(People::getId, People::getAddress, (value1, value2) -> value1));

1.2 、List转化为Map<Integer,Object>

复制代码
Map<Integer, People> map = peopleList.stream().collect(Collectors.toMap
(People::getId, each -> each, (value1, value2) -> value1));

1.3、List转化为Map<Integer,List>

复制代码
Map<Integer, List<People>> map = peopleList.stream().collect(Collectors
.groupingBy(People::getId));

1.4 List转化为Map<Integer,List>

复制代码
Map<Integer, List<String>> map3 = peopleList.stream().collect(Collectors.
toMap(People::getId, each -> Collections.singletonList(each.getName()), 
(value1, value2) -> {
			List<String> union = new ArrayList<>(value1);
			union.addAll(value2);
			return union;
}));

1.5、 List<Map<String,Object>> 转化为Map<String,Object>

复制代码
final static List<Map<String, Object>> mapStudentList = new ArrayList<>();
public static void main(String[] args) {
		Map<String, Object> map4 = mapStudentList.stream().collect(Collectors.toMap(each -> Objects.toString(each.get("id"), ""), each -> each.get("student"), (key1, key2) -> key1));
	}


	/**
	 * 初始化集合数据
	 */
	static {
		Student stu1 = new Student("0001", "张三", 12, "江苏南京");
		Student stu2 = new Student("0002", "李四", 14, "江苏无锡");
		Student stu3 = new Student("0003", "王二", 11, "浙江台州");
		Student stu4 = new Student("0004", "李五", 12, "浙江温州");


		Map<String, Object> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("student", stu1);

		Map<String, Object> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("student", stu2);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("student", stu3);

		Map<String, Object> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("student", stu4);

		mapStudentList.add(map1);
		mapStudentList.add(map2);
		mapStudentList.add(map3);
		mapStudentList.add(map4);
	}

1.6、List<Map<String,String>> 转化为Map<String,Map<String,String>>

复制代码
    final static List<Map<String, String>> listMapList = new ArrayList<>();


	public static void main(String[] args) {
		Map<String, Map<String, String>> map5 = listMapList.stream().collect(Collectors.toMap(each -> each.get("id"), each -> each, (key1, key2) -> key1));
		System.out.println("map5 = " + map5);

	}

	/**
	 * 初始化集合数据
	 */
	static {
		Map<String, String> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("name", "张三");
		map1.put("age", "12");
		map1.put("address", "江苏南京");

		Map<String, String> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("name", "李四");
		map2.put("age", "14");
		map2.put("address", "江苏无锡");


		Map<String, String> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("name", "王二");
		map3.put("age", "11");
		map3.put("address", "浙江台州");

		Map<String, String> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("name", "李五");
		map4.put("age", "12");
		map4.put("address", "浙江温州");


		listMapList.add(map1);
		listMapList.add(map2);
		listMapList.add(map3);
		listMapList.add(map4);
	}

1.7、List<Map<String,String>> 转化为Map<String,String>

复制代码
     final static List<Map<String, String>> listmapstringlist = new ArrayList<>();

	 public static void main(String[] args) {
     Map<String, String> map6 = listmapstringlist.stream().collect(Collectors.toMap(each -> each.get("id"), each -> each.get("name"), (key1, key2) -> key1));

	}

	/**
	 * 初始化集合数据
	 */
	static {
		Map<String, String> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("name", "张三");
		map1.put("age", "12");
		map1.put("address", "江苏南京");

		Map<String, String> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("name", "李四");
		map2.put("age", "14");
		map2.put("address", "江苏无锡");


		Map<String, String> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("name", "王二");
		map3.put("age", "11");
		map3.put("address", "浙江台州");

		Map<String, String> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("name", "李五");
		map4.put("age", "12");
		map4.put("address", "浙江温州");
		listmapstringlist.add(map1);
		listmapstringlist.add(map2);
		listmapstringlist.add(map3);
		listmapstringlist.add(map4);
	}


 list.add("c");
    list.add("a");
    list.add("b");
    list.add("d");

    List<User> userList = new ArrayList<>();
    userList.add(new User(new Long(1),"李世民","123lsm@163.com","男","110"));
    userList.add(new User(new Long(2),"宇文成都","123ywcd@163.com","男","111"));
    userList.add(new User(new Long(3),"裴元庆","123pyq@163.com","男","112"));
    userList.add(new User(new Long(4),"程咬金","123cyj@163.com","男","113"));
    userList.add(new User(new Long(5),"李元霸","123lyb@163.com","男","114"));
    userList.add(new User(new Long(6),"潇美娘","123xmn@163.com","女","11q"));
    userList.add(new User(new Long(6),"潇美娘","123xmn@163.com","女","11q"));



    for (int i = 0; i < list.size(); i++) {
        System.out.println("第一种遍历list方法" + list.get(i));
    }

    for (String s : list) {
        System.out.println("第二种遍历list方法:" + s);
    }

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        System.out.println("第三种遍历list方法:" + iterator.next());
    }

    list.forEach(new Consumer<String>() {
        @Override
        public void accept(String s) {
            System.out.printf("第四种遍历list方法:" + s + "\n");
        }
    });

    List<User> userList1 = new ArrayList<>();
    User user1 = new User();
    userList.forEach(user -> {
        user1.setId(user.getId());
        user1.setUserName(user.getUserName());
        user1.setSex(user.getSex());
        user1.setPhone(user.getPhone());
        user1.seteMail(user.geteMail());
        userList1.add(user1);
        System.out.println("第五种遍历方法########:"+userList1);

    });


    List<User> mm = userList.stream().filter(user -> user.getSex().equals("男")).collect(Collectors.toList());
    System.out.println("第六种:过滤掉不想要的列表,留下想要的列表########:");
    mm.forEach(System.out::println);

    List<String> gg = userList.stream().map(User::getSex).distinct().collect(Collectors.toList());
    System.out.println("=========gg对某个字段去重!");
    gg.forEach(System.out::println);

    List<String> g = userList.stream().map(user -> user.getUserName()).distinct().collect(Collectors.toList());
    System.out.println("=========g对某个字段去重!");
    g.forEach(System.out::println);

    List<User> users = userList.stream().distinct().collect(Collectors.toList());
    System.out.println("去除完全重复的数据!");
    users.forEach(System.out::println);

    ArrayList<User> arrayList = userList.stream().collect(Collectors.collectingAndThen(Collectors
            .toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getSex()))), ArrayList::new));
    System.out.println("arrayList根据指定的字段去除重复的数据");
    arrayList.forEach(System.out::println);


    List<Map<String,String>> mapList = new ArrayList<>();
    Map<String,String> mapL = new HashMap<>();
    Map<String,String> mapL2 = new HashMap<>();
    mapL.put("a","李世民");
    mapL.put("b","李元霸");
    mapL.put("c","秦叔宝");
    mapL2.put("a","李世民");
    mapList.add(mapL);
    mapList.add(mapL2);
    ArrayList<Map<String, String>> mapArrayList = mapList.stream().collect(Collectors.collectingAndThen(Collectors
            .toCollection(() -> new TreeSet<>(Comparator.comparing(map -> map.get("a")))), ArrayList::new));
    System.out.println("根据list集合中某个对象里的字段值去重:"+mapArrayList);

    /*
    * findAny和findFirst都是获取第一条信息,如果未找到则返回null
    * */
    User orElse = userList.stream().filter(user -> user.getUserName().equals("潇美娘")).findAny().orElse(null);
    System.out.println("获取存在潇美娘的第一条用户信息orElse:"+orElse);

    User anElse = userList.stream().filter(user -> user.getUserName().equals("罗成")).findFirst().orElse(null);
    System.out.println("获取不存在罗成的第一条用户信息anElse:"+anElse);

    System.out.println("下面介绍下map=========欢迎来到map家族!");

    Map<String, Integer> map = new HashMap<>();
    map.put("e", 2);
    map.put("h", 1);
    map.put("g", 9);
    map.put("f", 6);
    for (Map.Entry<String, Integer> m : map.entrySet()) {
        System.out.println("第一种map集合遍历:" + "KEY:" + m.getKey() + "\t" + "VALUE:" + m.getValue());
    }

    for (String key : map.keySet()) {
        System.out.println("第二种map集合遍历:" + "KEY:" + key + "\t" + "VALUE:" + map.get(key));
    }

    Iterator<Map.Entry<String, Integer>> iterator1 = map.entrySet().iterator();
    while (iterator1.hasNext()) {
        Map.Entry<String, Integer> entry = iterator1.next();
        System.out.println("第三种map集合遍历:" + "KEY:" + entry.getKey() + "\t" + "VALUE:" + entry.getValue());
    }
    map.forEach(new BiConsumer<String, Integer>() {
        @Override
        public void accept(String s, Integer s2) {
            System.out.println("第四种map集合遍历:" + "KEY:" + s + "\t" + "VALUE:" + s2);

        }
    });

    map.entrySet().forEach(entry -> System.out.println("第五种map集合遍历:" + "KEY:" + entry.getKey() + "\t" + "VALUE:" + entry.getValue()));

    map.values().forEach(s -> {
        System.out.println("直接获取map中的所有VALUE" + s);
    });

    map.forEach((k, v) -> {
        System.out.println("第六种最好的方法map集合遍历:" + "KEY:" + k + "\t" + "VALUE:" + v);
    });


    HashMap<String,Integer> maps = map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    maps.forEach((k,v)->System.out.println("对maps集合中value数据升序排序:"+"k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> mapsS = map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o2, LinkedHashMap::new));
    mapsS.forEach((k,v)->System.out.println("对mapsS集合中value数据降序排序:"+"k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map0 = map.entrySet().stream().sorted((Map.Entry.comparingByValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map0.forEach((k,v)->System.out.println("对map0集合中value数据升序排序:" + "k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map1 = map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByKey().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map1.forEach((k,v)-> System.out.println("对map1集合中key降序排序:" + "k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map2 = map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map2.forEach((k,v)-> System.out.println("对map集合中value降序排序:" + "k:"+k+"\t"+"v:"+v));


}

@Data
public class TestDemo {
 
    //获取第pageNum页数据
    public static List<?> partition(ArrayList<?> list, int pageSize, int pageNum) {
        //将List按照pageSize拆分成多个List
        List<? extends List<?>> partition = Lists.partition(list, pageSize);
        //总页数
        int pages = partition.size();
        pageNum = pageNum <= 0 ? 0 : (pageNum <= (pages - 1) ? pageNum-1 : (pages - 1));
        return partition.get(pageNum);
    }
 
    public static void main(String[] args) {
        List<TestDemo> list = new ArrayList<>();
        list.add(new TestDemo(1L,11L,100L));
        list.add(new TestDemo(2L,11L,600L));
        list.add(new TestDemo(3L,33L,333L));
        list.add(new TestDemo(4L,33L,null));
        list.add(new TestDemo(5L,44L,null));
        //(一、转Map)如果有重复的key,则保留key1,舍弃key2
        Map<Long, TestDemo> map = list.stream().collect(Collectors.toMap(TestDemo::getId, item -> item, (key1, key2) -> key1));
 
        //(二、排序)
        // Comparator.comparing(类::属性一).reversed(); 得到排序结果后再排序
        //Comparator.comparing(类::属性一,Comparator.reverseOrder());是直接进行排序
        //升序、空值排在最前面、reversed反转排序
        List<TestDemo> sortList = list.stream().sorted(
                Comparator.comparing(TestDemo::getTotal, Comparator.nullsFirst(Long::compareTo)).reversed()
        ).collect(Collectors.toList());
        //属性一升序,属性二降序
        sortList = list.stream().sorted(
                Comparator.comparing(TestDemo::getId).thenComparing(TestDemo::getGroup, Comparator.reverseOrder())
        ).collect(Collectors.toList());
 
        //(三、分组)
        Map<Long, List<TestDemo>> groupMapList = list.stream().collect(Collectors.groupingBy(TestDemo::getGroup));
        Map<Long, TestDemo> groupMapObject = list.stream().collect(
                //取分组中的一条数据
                Collectors.groupingBy(TestDemo::getGroup, Collectors.collectingAndThen(Collectors.toList(), item -> item.get(0)))
        );
        //分组求和得到新集合
        List<TestDemo> groupSumList = new ArrayList<>();
        list.parallelStream().collect(Collectors.groupingBy(TestDemo::getGroup, Collectors.toList()))
                .forEach((id, groupList) -> {
                    groupList.stream().reduce(
                            (a, b) ->  new TestDemo(a.getId(), a.getGroup(), a.getTotal(), b.getTotal())
                    ).ifPresent(groupSumList::add);
                });
 
        //(四、去重)
        List<String> stringList = new ArrayList<String>() {{ add("A"); add("A"); add("B"); add("B"); add("C"); }};
        stringList = stringList.stream().distinct().collect(Collectors.toList());
        //对象属性去重
        List<TestDemo>  distinctList = list.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(()
                        -> new TreeSet<>(Comparator.comparing(TestDemo::getGroup))), ArrayList::new));
 
        //(五、提取)
        List<Long> groupNumList = list.stream()
            .map(TestDemo::getGroup) //流转化为Long
            .distinct() //去重
            .collect(Collectors.toList());
 
        //(六、过滤)
        List<TestDemo> filterList = list.stream().filter(item -> item.getTotal() != null && item.getTotal() < 200).collect(Collectors.toList());
        List<TestDemo> filtersList = list.stream()
                .filter(item -> {//多条件过滤
                    if(item.getTotal() == null) {
                        return false;
                    }
                    if (item.getTotal() > 200 && item.getTotal() < 400) {
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
 
        //(七、取值)
        // 平均数
        Double avg1 = list.stream().filter(item -> item.getTotal() != null).mapToLong(TestDemo::getTotal).average().orElse(0);//为空的不参与计算
        Double avg2 = list.stream().filter(item -> {
            if(item.getTotal() == null) { //为空的参与计算
                item.setTotal(0L);//避免计算时报空指针错误
            }
            return true;
        }).collect(Collectors.averagingLong(TestDemo::getTotal));
        // 最大值
        Long max = list.stream().mapToLong(TestDemo::getTotal).max().orElse(0);
        // 最小值
        Long min = list.stream().mapToLong(TestDemo::getTotal).min().orElse(0);
        //求和
        Long sum = list.stream().mapToLong(TestDemo::getTotal).sum();
    }
 
    private Long id;
    private Long group;
    private Long total;
    public TestDemo(){}
 
    public TestDemo(Long id, Long group, Long total) {
        this.id = id;
        this.group = group;
        this.total = total;
    }
 
    public TestDemo(Long id, Long group, Long aTotal, Long bTotal) {
        this.id = id;
        this.group = group;
        this.total = (aTotal==null ? 0 : aTotal) + (bTotal==null ? 0 : bTotal);
    }
}
相关推荐
许白掰1 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
longze_75 小时前
Ubuntu连接不上网络问题(Network is unreachable)
linux·服务器·ubuntu
Dirschs5 小时前
【Ubuntu22.04安装ROS Noetic】
linux·ubuntu·ros
qianshanxue115 小时前
ubuntu 操作记录
linux
AmosTian8 小时前
【系统与工具】Linux——Linux简介、安装、简单使用
linux·运维·服务器
荔枝吻8 小时前
【保姆级喂饭教程】Windows下安装Git Flow
windows·git·git flow
这我可不懂10 小时前
Python 项目快速部署到 Linux 服务器基础教程
linux·服务器·python
车车不吃香菇11 小时前
java idea 本地debug linux服务
java·linux·intellij-idea
tan77º11 小时前
【Linux网络编程】Socket - TCP
linux·网络·c++·tcp/ip