1 回答

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
自從在 Java 8中添加 API 以來,該設(shè)計(jì)模式已經(jīng)過時(shí)Stream。標(biāo)準(zhǔn)現(xiàn)在由Predicate接口定義并由filter方法執(zhí)行。
public static void main(String... args) {
Person john = new Person("John Doe", Gender.MALE, MaritalStatus.MARRIED);
Person jane = new Person("Jane Doe", Gender.FEMALE, MaritalStatus.MARRIED);
Person joe = new Person("Joe Bloe", Gender.MALE, MaritalStatus.SINGLE);
Set<Person> husbands = Stream.of(john, jane, joe)
.filter(person -> person.gender == Gender.MALE)
.filter(person -> person.maritalStatus == MaritalStatus.MARRIED)
.collect(Collectors.toSet());
}
enum Gender { MALE, FEMALE }
enum MaritalStatus { MARRIED, SINGLE }
static class Person {
final String name;
final Gender gender;
final MaritalStatus maritalStatus;
Person(String name, Gender gender, MaritalStatus maritalStatus){
this.name = name;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
}
添加回答
舉報(bào)