java8特性之集合stream式操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010739551/article/details/89851034

一、测试类

public class Student {

    public Student(String city) {
        this.city = city;
    }

    private String city;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("chengdu"));
        studentList.add(new Student("beijing"));
        studentList.add(new Student("chengdu"));
        studentList.add(new Student("shanghai"));

        //常规操作
        long count = 0;
        for(Student student : studentList){
            if(student.getCity().equals("chengdu")){
                count++;
            }
        }
        System.out.println(count);

        //======================================

        //java8 stream流操作
        count = studentList.stream().filter((s -> s.getCity().equals("chengdu"))).count();
        System.out.println(count);
        boolean result = studentList.stream().anyMatch(s -> s.getCity().equals("beijing"));
        System.out.println(result);
    }

}

二、测试结果

猜你喜欢

转载自blog.csdn.net/u010739551/article/details/89851034