无法在流上调用过滤方法

时间:2015-08-21 09:16:52

标签: java filter lambda predicate

我在从Oracel做教程@Java SE 8时感到困惑 http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html

我试图使用过滤器过滤人员列表时,卡住@Lambda表达式和集合。来自SearchCriteria的Mine getCriteria()方法返回谓词,而过滤器接受谓词 - 哪里出错?

感谢您的帮助

SearchCriteria.class

    private final Map<String, Predicate<Person>> searchMap = new HashMap<>();

private SearchCriteria() {
    super();
    initSearchMap();
}

public static SearchCriteria getInstance() {
    return new SearchCriteria();
}

private void initSearchMap() {

    Predicate<Person> allDrivers = p -> p.getAge() >= 16;
    Predicate< Person> allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25;
    Predicate< Person> allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65;

    searchMap.put("allDrivers", allDrivers);
    searchMap.put("allDraftees", allDraftees);
    searchMap.put("allPilots", allPilots);
}

public Predicate<Person> getCriteria(String predicateName) {

    Predicate<Person> result;
    result = searchMap.get(predicateName);

    // result = searchMap.get(predicateName);
    // Optional<Predicate<Person>> optPredicatePerson =
    // Optional.of(searchMap.get(predicateName));

    // if (optPredicatePerson.isPresent()) {
    // result = optPredicatePerson.get();
    // }

    // Predicate<Person> z = p -> false;
    //
    // optPredicatePerson.orElse(z);

    // return result;

    if (result == null) {
        System.out.println("Search Criteria not found... ");
        System.exit(1);
    }

    return result;
}

public static void main(String ... args){

    List<Person> pl = Person.createShortList();

    SearchCriteria search = SearchCriteria.getInstance();
    System.out.println("\n=== Western Pilot Phone List ===");

    pl.stream().filter(search.getCriteria("allPilots")).forEach(Person::printWesterName);

}

0 个答案:

没有答案