java - 用谓词组合Java中两个相似的方法

标签 java lambda predicate

就主体而言,我有两个类似的方法,但参数数量不同,并且内部有一个额外的条件。我知道有一种方法可以使用谓词将它们合并到一个方法中,但我不完全确定如何实现它。解决这个问题的最佳方法是什么?

public boolean checkIfAllCodesAreUnique(List<String> bsnCodes)
{
    List<Businesscode> codes = ConverterUtil.iterableToList(businessCodeService.findAll());
    if(codes != null && !codes.isEmpty() && bsnCodes != null && !bsnCodes.isEmpty())
        for (String code : bsnCodes)
            if (codes.stream().anyMatch(obj -> code.equals(obj.getCode())))
                return false;
    return true;
}

public boolean checkIfAllCodesAreUnique(List<String> bsnCodes, int idRole)
{
    List<Businesscode> codes = ConverterUtil.iterableToList(businessCodeService.findAll());
    if(codes != null && !codes.isEmpty() && bsnCodes != null && !bsnCodes.isEmpty())
        for (String code : bsnCodes)
            if (codes.stream().anyMatch(obj -> code.equals(obj.getCode()) && obj.getId() != idRole))
                return false;
    return true;
}

最佳答案

public boolean checkIfAllCodesAreUnique(List<String> bsnCodes) {
    return isAllCodesAreUnique(bsnCodes, businessCode -> true);
}

public boolean checkIfAllCodesAreUnique(List<String> bsnCodes, int idRole) {
    return isAllCodesAreUnique(bsnCodes, businessCode -> businessCode.getId() != idRole);
}

private boolean isAllCodesAreUnique(List<String> bsnCodes, Predicate<Businesscode> checkRole) {
    List<Businesscode> businessCodes = Optional.ofNullable(ConverterUtil
            .iterableToList(businessCodeService.findAll())).orElse(List.of());

    for (String bsnCode : Optional.ofNullable(bsnCodes).orElse(List.of())) {
        if (businessCodes.stream()
                         .filter(businessCode -> bsnCode.equals(businessCode.getCode()))
                         .anyMatch(checkRole))
            return false;
    }

    return true;
}

关于java - 用谓词组合Java中两个相似的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70767337/

相关文章:

java - 如何找出这个ConcurrentModificationException崩溃的地方?

java - 使用 Lettuce 响应式(Reactive)命令订阅 Redis channel (pubsub)

c# - 更改 LambdaExpression 中的参数名称只是为了显示

java - 当服务器消失时强制断开 TCP 连接

java - Android - Node.getNodeValue() 在存在 ' 时被截断

c++ - 累加 vector 的绝对值

c#:Enumerable 类中的 Where()、OrderBy() 和 Select() 不应该采用委托(delegate)类型、lambda 表达式或匿名类型作为参数

c++ - std::greater<int>() 和 std::greater<int> 之间的区别?

c# - 如何编写复杂 SQL 但使用谓词(通过 Dapper)

java - 使用泛型和继承来谓词 java 8