public class Demo {
private Integer id;
private Integer num;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public String toString() {
return "Demo{" +
"id=" + id +
", num=" + num +
'}';
}
public Demo(Integer id, Integer num) {
this.id = id;
this.num = num;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class test03 {
public static void main(String[] args) {
List<Demo> list = new ArrayList<>();
list.add(new Demo(1,1));
list.add(new Demo(1,3));
list.add(new Demo(2,2));
list.add(new Demo(3,2));
list.add(new Demo(3,8));
//统计集合中符合条件的数据数量
long count = list.stream().filter(s -> s.getId() == 1).count();
//统计集合中符合条件的数据
List<Demo> demoList = list.stream().filter(s -> s.getNum() == 2).collect(Collectors.toList());
//统计集合中符合条件的第一条数据
//Java 8 新特性 Optional 类是一个可以为null的容器对象
Optional<Demo> demo = list.stream().filter(s -> s.getNum() == 2).findFirst();
System.out.println(count);
System.out.println(demoList);
System.out.println(demo);
}
}
运行结果如下: