栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

List<E>转Map<String,List<E>>

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

List<E>转Map<String,List<E>>

实体类 

package com.example.demo.entity;

public class Person {
    private Integer age;
    private String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + ''' +
                '}';
    }
}

测试类

 @Test
    void contextLoads() {
        List personList = new ArrayList<>();
        personList.add(new Person(1,""));

        personList.add(new Person(3,""));
        personList.add(new Person(4,"小红"));

        Map> groups = personList.stream().collect(Collectors.groupingBy(ele -> ele.getName(), Collectors.mapping(Function.identity(), Collectors.toList())));

        groups.forEach((k,v)->{
            if(k.isEmpty()){
                System.out.println(k+"ok===" + v);
            }else{
                System.out.println(k+"===" + v);
            }
        });
        System.out.println(groups);
        System.out.println("============================");

        List people = new ArrayList<>();
        people.add(new Person(1,null));

        people.add(new Person(3,""));
        people.add(new Person(4,"小红"));

        Map, List> group = people.stream().collect(Collectors.groupingBy(ele -> Optional.ofNullable(ele.getName()), Collectors.mapping(Function.identity(), Collectors.toList())));

        group.forEach((k,v)->{
            if(k.filter(e->e.isEmpty()).isPresent()){
                System.out.println(k+"ok===" + v);
            }else{
                System.out.println(k+"===" + v);
            }
        });
        System.out.println(group);
    }

 注意:

使用groupBy的时候一定要确保分组的字段不是null的,可以是empty但是不能是null,否则会报错,如下图

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/723287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号