java8 stream list工具

1.list排序

//测试集合对象
public class Student {
private String name;
private String sex;
private double height;
private double weight;
private int age;
Student(){}
Student(String name,String sex,double height,double weight,int age){
this.name = name;
this.sex = sex;
this.height = height;
this.weight = weight;
this.age = age;
}
}

public static void main(String[] args) {
    List studentList = Lists.newArrayList();
    studentList.add(new Student("小王3","男",50,50,50));
    //添加数据源
    for(int i = 0;i<10;i++){
        studentList.add(new Student("小明"+i,"男"+i,i+1,i+2,i+3));
    }

    //排序-正序
    studentList.sort(Comparator.comparing(Student::getAge,(x,y)->{
            if(x>y){
                return 1;
            }else if(x==y){
                return 0;
            }else{
                return -1;
            }
    }));

    //排序-倒序
    studentList.sort(Comparator.comparing(Student::getAge,(x,y)->{
        if(x>y){
            return 1;
        }else if(x==y){
            return 0;
        }else{
            return -1;
        }
    }).reversed());

    //多条件排序-正序
    studentList.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getHeight));

    studentList.forEach(student ->{
        System.out.println(student.getName()+":"+student.getAge());
    });
}

2.list抽取属性生产新的List或Map

public static void main(String[] args) {
List studentList = Lists.newArrayList();
studentList.add(new Student(“小王3”,“男”,50,3,3));
//添加数据源
for(int i = 0;i<10;i++){
studentList.add(new Student(“小明”+i,“男”+i,i+1,i+2,i+3));
}
//抽取对象属性形成新的list
List list = studentList.stream().map(Student::getAge).collect(Collectors.toList());
//抽取对象属性形成map
Map map1 = studentList.stream().collect(Collectors.toMap(Student::getAge,a->a,(k1,k2)->k1));
Map map2 = studentList.stream().collect(Collectors.toMap(Student::getAge,Student::getName,(k1,k2)->k1));
}

3.list过滤、分组

public static void main(String[] args) {
    List studentList = Lists.newArrayList();
    studentList.add(new Student("小王3","男",50,3,3));
    //添加数据源
    for(int i = 0;i<10;i++){
        studentList.add(new Student("小明"+i,"男"+i,i+1,i+2,i+3));
    }
    //过滤
  List lsit =   studentList.stream().filter(student-> student.getAge()>6).collect(Collectors.toList());
    //分组
  Map> map =  studentList.stream().collect(Collectors.groupingBy(Student::getAge));
  
}

你可能感兴趣的:(工具)