Java8 Stream

/**
 * 通過流和函數式編程的方法來完成查詢過濾
 */
public class Test10Stream {
    public static void main(String[] args) {
        Person person1 = new Person("zhangsan", 20);
        Person person2 = new Person("lisi", 25);
        Person person3 = new Person("wangwu", 30);

        List<Person> list = Arrays.asList(person1, person2, person3);

        Test10Stream Test = new Test10Stream();
        List<Person> resultList = Test.getPersonsByUsername("zhangsan", list);
        resultList.forEach(person -> System.out.println("persons 1 = [" + person + "]"));

        System.out.println("--------------------");

        List<Person> resultList2 = Test.getPersonsByAge(25, list);
        resultList2.forEach(person -> System.out.println("persons 2 = [" + person + "]"));

        System.out.println("--------------------");

        List<Person> resultList3 = Test.getPersonsByAge2(25, list, (ageOfPerson, personList) ->
                personList.stream().filter(person -> person.getAge() >= ageOfPerson).collect(Collectors.toList()));
        resultList3.forEach(person -> System.out.println("persons 3 = [" + person + "]"));
    }

    //通過name查詢列表中符合條件的對象
    public List<Person> getPersonsByUsername(String name, List<Person> persons){
        //先轉換成流,過濾流裏面每一個對象,把名字符合我們要求的過濾出來,得到一個流,最後把這些流組合成一個集合
        return persons.stream().filter(person -> person.getName().equals(name)).collect(Collectors.toList());
    }

    //通過age查詢列表中符合條件的對象
    public List<Person> getPersonsByAge(int age, List<Person> persons){
        //先定義BiFunction
        //三個參數分別是年齡,輸入的用戶集合,輸出的用戶集合結果
        BiFunction<Integer, List<Person>, List<Person>> biFunction = (ageOfPerson, personList) -> {
            return  personList.stream().filter(person -> person.getAge() >= ageOfPerson).collect(Collectors.toList());
        };
        //簡寫如下:
        BiFunction<Integer, List<Person>, List<Person>> biFunction2 = (ageOfPerson, personList) ->
              personList.stream().filter(person -> person.getAge() >= ageOfPerson).collect(Collectors.toList());

        //再應用bifunction
        return biFunction2.apply(age, persons);
    }

    //改進版
    public List<Person> getPersonsByAge2(int age, List<Person> persons, BiFunction<Integer, List<Person>, List<Person>> biFunction){
        //再應用bifunction
        return biFunction.apply(age, persons);
    }

}

class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章