使用方法引用来检查布尔值匹配而不是 lambda

Use method reference to check boolean value match instead of lambda

使用方法参考进行比较 boolean

而不是(t->t),我想使用方法引用。方法参考适用于非布尔值匹配,如下所述。

完整代码:

public class AccountListTest {
    public static void main(String[] args){
        List<Account> list = new ArrayList<>();
        Account a1 = new Account(true, "Test1");
        list.add(a1);
        Account a2 = new Account(false, "Test2");
        list.add(a2);

        if(list.stream().map(Account::getName).anyMatch("test1"::equalsIgnoreCase)){
            System.out.println("Contain Account with name Test1");
        }

        if(list.stream().map(Account::isActive).anyMatch(t->t)){
            System.out.println("Have Active Account");
        }
    }
}

class Account{
    private boolean active;
    private String name;
    public Account(boolean active, String name) {
        super();
        this.active = active;
        this.name = name;
    }   
}

感谢任何帮助!谢谢!

将第二个条件写成更有意义:

if(list.stream().anyMatch(Account::isActive)) {
    System.out.println("Have Active Account");
}

不需要先调用map

如前所述,根据您的需要,您的最佳选择是:

list.stream().allMatch(Account::isActive)
list.stream().anyMatch(Account::isActive)
!list.stream().noneMatch(Account::isActive)

等等。

但要直接回答您的问题,您可以使用:

list.stream().map(Account::isActive).anyMatch(Boolean::valueOf)