java - 使用方法引用来检查 boolean 值匹配而不是 lambda

标签 java lambda java-8 method-reference

使用方法引用比较boolean

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

完整代码:

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

关于java - 使用方法引用来检查 boolean 值匹配而不是 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55492408/

相关文章:

c# - 这个 object-lifetime-extending-closure 是 C# 编译器错误吗?

java - Lambda 和转换交集类型(Eclipse 编译器错误)

java - 为什么保存的图片这么小?

c# - new Action(() => someCombobox.Text = "x"有什么问题)

c# - 为什么在没有返回值的 lambda 中添加 throw 会被推断为 Func<T> 而不是 Action?

java - 如何加快素数计算速度?

java - 获取幸运号码

yyyymmddhhmmss 的 Java 正则表达式

java - 在 TextView 中显示评论/在编辑 View 中接受评论以在测验应用程序中使用

java - 将 BouncyCaSTLe 与 GnuPG 2. 1's ` pubring.kbx` 文件一起使用