java8对list集合中数据进行过滤对集合中的某个对象多个属性排序

时间:2025-04-02 20:16:27

java 8中对集合过滤的方法主要是用stream中的filter 进行数据筛选

 public static void main(String[] args) throws Exception{
        ArrayList<Car> list = new ArrayList<>();
        for(int i=0;i<100;i++){
            Car car = new Car();
            (i);
            ("第一条"+i);
            (car);
        }
        List<Car> collect = ().filter(e -> () >= 50&&()<55).limit(10).collect(());
        for(Car c:collect){
            (());
        }
    }

也可以了对集合排个序
sorted((Car::getId)这个是对id升序 sorted((Car::getId).reversed() 这个是对id倒序

 public static void main(String[] args) throws Exception{
        ArrayList<Car> list = new ArrayList<>();
        for(int i=0;i<100;i++){
            Car car = new Car();
            (i);
            ("第一条"+i);
            (car);
        }
        List<Car> collect = ().filter(e -> () >= 50&&()<55).limit(10).sorted((Car::getId).reversed()).collect(());
        for(Car c:collect){
            (());
        }
    }

对集合中对象的多个属性排序(写多个sorted方法 把优先排序的字段写到最后 优先级依次向前)

public static void main(String[] args) throws Exception{
        ArrayList<Car> list = new ArrayList<>();
        (new Car(1,"1",1));
        (new Car(2,"1",1));
        (new Car(3,"1",2));
        (new Car(4,"1",3));
        (new Car(5,"1",1));
        (new Car(6,"1",1));
        (new Car(7,"1",1));
        (new Car(8,"1",3));
        (new Car(9,"1",1));
        (new Car(10,"1",2));
        (new Car(11,"1",1));
        (new Car(12,"1",1));
        (new Car(13,"1",2));
        (new Car(14,"1",2));
        (new Car(15,"1",3));
        List<Car> collect = ().filter(e -> () >= 5&&()<15).limit(10)
                .sorted((Car::getType)).sorted((Car::getId).reversed())
                .collect(());
        for(Car c:collect){
            (());
        }
    }
ublic class Car {
        Integer id;
        String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
         = id;
    }

    public String getName() {
        return name;
    }

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

结果
50
51
52
53
54