1. 程式人生 > >lambda的應用場景實例

lambda的應用場景實例

會有 條件 lam == 替代 check sele docs 而且

定義一個POJO類

package com.kotlin.demo.lambda;

import java.time.LocalDate;

public class Person {
    public enum Sex {
        MALE, FEMALE
    }
    String name;
    int age;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public Person(String name, int age, LocalDate birthday, Sex gender, String emailAddress) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.gender = gender;
        this.emailAddress = emailAddress;
    }

    public Person() {
    }

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

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

    public int getAge() {
        return this.age;
    }

    public String getName() {
        return name;
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    public Sex getGender() {
        return gender;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

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

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

    public void setBirthday(LocalDate birthday) {
        this.birthday = birthday;
    }

    public void setGender(Sex gender) {
        this.gender = gender;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public void printPerson() {
        System.out.println("print person:" + this.toString());
    }

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

第一種情況:超過指定年齡的人

public static void printPersonsOlderThan(List<Person> roster, int age) {
    for (Person p : roster) {
        if (p.getAge() >= age) {
            p.printPerson();
        }
    }
}
List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

//  通過常規的方法來實現特定的篩選
PersonUtil.printPersonsOlderThan(personList, 30);

第二種情況:篩選一定年齡範圍的人

public static void printPersonsWithinAgeRange(List<Person> roster, int low, int high) {
    for (Person p : roster) {
        if (low <= p.getAge() && p.getAge() < high) {
            p.printPerson();
        }
List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

PersonUtil.printPersonsWithinAgeRange(personList, 40, 60);

第三種情況:不知道篩選條件是什麽,為了更好的適應將來的情況。定義篩選條件類

public interface CheckPerson {
    boolean test(Person p);
}
public class CheckPersonEligibleForSelectiveService implements CheckPerson {
    @Override
    public boolean test(Person p) {
        return p.gender == Person.Sex.MALE &&
                p.getAge() >= 20 &&
                p.getAge() <= 40;
    }
}

public static void printPersons(List<Person> roster, CheckPerson tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}
List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

// 采用已經實現的CheckPerson類來篩選person
PersonUtil.printPersons(personList, new CheckPersonEligibleForSelectiveService());

第四種方式:通過匿名內部類的方式來實現定義的篩選接口,以適應需要的情況

List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

// 通過匿名內部類的形式來實現篩選條件
PersonUtil.printPersons(personList, new CheckPerson() {
    @Override
    public boolean test(Person p) {
        return p.getGender() == Person.Sex.FEMALE
                && p.getAge() >= 40
                && p.getAge() <= 80;
    }
});

第五種方式:通過lambda的方式來替代匿名內部類

List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

// 通過lambda的方式來實現篩選
PersonUtil.printPersons(personList,
        p -> p.getGender() == Person.Sex.MALE
                && p.getAge() >= 40
                && p.getAge() <= 80);

第六種方式:不用自己定義篩選條件類,而采用JDK自帶的Funcation

public static void printPersonsWithPredicate(List<Person> roster, Predicate<Person> tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}
List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 20, Person.Sex.MALE));
personList.add(new Person("name2", 30, Person.Sex.FEMALE));
personList.add(new Person("name3", 40, Person.Sex.MALE));
personList.add(new Person("name4", 50, Person.Sex.FEMALE));
personList.add(new Person("name5", 60, Person.Sex.MALE));
personList.add(new Person("name6", 70, Person.Sex.FEMALE));
personList.add(new Person("name7", 80, Person.Sex.MALE));

PersonUtil.printPersonsWithPredicate(personList,
        p -> p.getGender() == Person.Sex.MALE
                && p.getAge() >= 40
                && p.getAge() <= 80);

Stream的方式處理更多的情況

// 通過lambda的stream來篩選並重新設值
 personList.stream()
         .filter(person -> person.getGender() == Person.Sex.MALE)
         .forEach(person -> person.setEmailAddress("[email protected]"));
         
 String s = personList.stream()
        .filter(person -> person.getGender() == Person.Sex.MALE)
        .map(person -> person.getName())
        .findFirst()
        .get();


總結:通過以上的例子,讓我們明白,在有些時候為了代碼的健壯性,通常會定義一些中間類來達到我們想要的目標。雖然通過匿名內部類的方式能達到很好的效果,但是其冗余的代碼量,增加了代碼高度。而采用lambda的形式,使得代碼更精簡。同時,lambda只讓我們實現具體的代碼邏輯,至於如何使用這些代碼則交給了編譯器來處理,而不需要我們來指明這些代買具體的執行方式。而且隨著編譯器的發展,可能會有更好的優化機制。這樣就使得我們只編寫邏輯,而不參與代碼的具體執行方式。


參考地址:https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html


lambda的應用場景實例