首页 > 其他 > 详细

List集合流处理类型小结

时间:2019-04-19 18:58:59      阅读:276      评论:0      收藏:0      [点我收藏+]

本文为博主原创,未经允许不得转载

对应实体类

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Student {
    
    private String name;
    
    private int age;
    
    private String className;

    private String birthday;
}

1.根据字段取出某一个字段属性的集合

List<Student> studentList = new ArrayList<>();
     List<int> newList = studentList.stream().map(Student::getAge).collect(Collectors.toList());
     for (Student student : newList) {
        System.out.println(student.getName()+"---"+student.getAge());
    }

2。List根据某个字段排序

List<Student> studentList = new ArrayList<>();
    List<Student> newList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
    for (Student student : newList) {
    System.out.println(student.getName()+"---"+student.getAge());
}

3.List根据某个字段排序降序

List<Student> list = new ArrayList<>();
    list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

4.获取某一字段属性值对应的数据集合

List<Student> resultList = studentList.stream()
        .filter((Student stu) -> area.equals(stu.getAge()))
        .collect(Collectors.toList());

5.根据某个字段值获取出对应的对象   

Student stu = studentList.stream()
        .filter(p -> "2018-08-12 12:10".equals(p.getBirthday()))
        .findAny().orElse(null);

代码是很简答,很优雅的

解释一下

list.stream(): 是把list集合转化为stream集合

sorted(): 进行排序,其中Comparator.comparing(Student::getAge)表示按照年纪排序,

.reversed()表示是逆序,因为默认情况下,不加.reversed 是升序的

collect(Collectors.toList()): 再次将排序后的stream集合转化为list集合

.findAny()表示将其中任意一个返回;

.orElse(null)表示如果一个都没找到返回null

List集合流处理类型小结

原文:https://www.cnblogs.com/zjdxr-up/p/10737549.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!