• Java8 常用方法总结


    Java8 使用 stream().map()提取List对象的某一列值及排重

    List对象类(StudentInfo)

    @Data
    @Builder
    @AllArgsConstructor
    @RequiredArgsConstructor
    public class StudentInfo implements Comparable<StudentInfo> {
        //名称
        private String name;
    
        //性别 true男 false女
        private Boolean gender;
    
        //年龄
        private Integer age;
    
        //身高
        private Double height;
    
        //出生日期
        private LocalDate birthday;
    }

    测试数据

    //测试数据,请不要纠结数据的严谨性
    List<StudentInfo> studentList = new ArrayList<>();
    studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
    studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
    studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
    studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));

    提取某一列(以name为例)

    //从对象列表中提取一列(以name为例)
    List<String> nameList = studentList.stream().map(StudentInfo::getName).collect(Collectors.toList());

     提取age列并排重(使用distinct()函数)

    //从对象列表中提取age并排重
    List<Integer> ageList = studentList.stream().map(StudentInfo::getAge).distinct().collect(Collectors.toList());

    Java8 使用 stream().sorted()对List集合进行排序

    集合对像定义

    集合对象以学生类(StudentInfo)为例,有学生的基本信息,包括:姓名,性别,年龄,身高,生日几项。

    使用stream().sorted()进行排序,需要该类实现 Comparable 接口,该接口只有一个方法需要实现,如下:

    public int compareTo(T o);

    排序

    //按年龄排序(Integer类型):使用年龄进行升序排序
    List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());
    //按年龄排序(Integer类型):使用年龄进行降序排序(使用reversed()方法)
    List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());
    //按年龄排序(Integer类型): 使用年龄进行降序排序,年龄相同再使用身高升序排序
    List<StudentInfo> studentsSortName = studentList.stream()
        .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
        .collect(Collectors.toList());

     Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

    //查找身高在1.8米及以上的男生
    List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
  • 相关阅读:
    arguments.callee
    React成长路之--项目搭建
    JS判断页面是否被iframe及禁止页面被iframe
    flex实现常见布局
    移动端 js 实现文章的分页、翻页
    移动端开发时,搜索框聚焦时键盘出现“搜索”两字,实现友好操作
    JSON详解
    50SQL练习
    设计模式之单例模式
    Spring REST 入门教程
  • 原文地址:https://www.cnblogs.com/struggleVIP/p/13305844.html
Copyright © 2020-2023  润新知