java 8中对集合过滤的方法主要是用stream中的filter 进行数据筛选
public static void main(String[] args) throws Exception{
ArrayList list = new ArrayList<>();
for(int i=0;i<100;i++){
Car car = new Car();
car.setId(i);
car.setName("第一条"+i);
list.add(car);
}
List collect = list.stream().filter(e -> e.getId() >= 50&&e.getId()<55).limit(10).collect(Collectors.toList());
for(Car c:collect){
System.out.println(c.getId());
}
}
也可以了对集合排个序
sorted(Comparator.comparingInt(Car::getId)这个是对id升序 sorted(Comparator.comparingInt(Car::getId).reversed() 这个是对id倒序
public static void main(String[] args) throws Exception{
ArrayList list = new ArrayList<>();
for(int i=0;i<100;i++){
Car car = new Car();
car.setId(i);
car.setName("第一条"+i);
list.add(car);
}
List collect = list.stream().filter(e -> e.getId() >= 50&&e.getId()<55).limit(10).sorted(Comparator.comparingInt(Car::getId).reversed()).collect(Collectors.toList());
for(Car c:collect){
System.out.println(c.getId());
}
}
对集合中对象的多个属性排序(写多个sorted方法 把优先排序的字段写到最后 优先级依次向前)
public static void main(String[] args) throws Exception{
ArrayList list = new ArrayList<>();
list.add(new Car(1,"1",1));
list.add(new Car(2,"1",1));
list.add(new Car(3,"1",2));
list.add(new Car(4,"1",3));
list.add(new Car(5,"1",1));
list.add(new Car(6,"1",1));
list.add(new Car(7,"1",1));
list.add(new Car(8,"1",3));
list.add(new Car(9,"1",1));
list.add(new Car(10,"1",2));
list.add(new Car(11,"1",1));
list.add(new Car(12,"1",1));
list.add(new Car(13,"1",2));
list.add(new Car(14,"1",2));
list.add(new Car(15,"1",3));
List collect = list.stream().filter(e -> e.getId() >= 5&&e.getId()<15).limit(10)
.sorted(Comparator.comparingInt(Car::getType)).sorted(Comparator.comparingInt(Car::getId).reversed())
.collect(Collectors.toList());
for(Car c:collect){
System.out.println(c.toString());
}
}
ublic class Car {
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
结果
50
51
52
53
54