繁体   English   中英

如何在JAVA中结合两种方法?

[英]How to combine two methods in JAVA?

我有两个方法返回两个值。 该方法几乎是相同的,所以我想将它们组合为单个方法并进行操作以返回不同的值,但不确定是否有用?

有人可以告诉我这种方法可以转换为单一方法吗?

private boolean getFirst(List<Apples> apples) {

        boolean isOrange  = false;
        if (apples != null) {
            for (Apples apple : apples) {
                String type = apple.getFruit();
                boolean isApple = StringUtils.equalsIgnoreCase(type, ORANGE);
                if (!isApple) {
                    isOrange = true;
                }
            }
        }
        return isOrange;
    }



 private boolean getSecond(List<Apples> apples) {

        boolean isAppletype  = false;
        if (apples != null) {
            for (Apples apple : apples) {
                 String type = apple.getFruit();
                boolean isApple = StringUtils.equalsIgnoreCase(type, ORANGE);
                 if (isApple) {
                    isAppletype = true;
                }
            }
        }
        return isAppletype;
    }

您可以为此使用流:

List<Apple> list = ...;

// First method
list.stream().anyMatch((e) -> !StringUtils.equalsIgnoreCase(e.getFruit(), ORANGE));
// Second method
list.stream().anyMatch((e) -> StringUtils.equalsIgnoreCase(e.getFruit(), ORANGE));

是的,您可以肯定地将这些方法合并到一个新方法中,该方法可以对其用途进行更通用的...

例如,如果我将方法重命名为isThisFruitPresentInTheList,请原谅我使用的名称约定:) ...

然后,您可以将列表传递给方法,然后将要查找的水果作为第二个参数,如果列表中存在水果,则该方法将返回true,否则返回false。

例:

 private boolean isThisFruitPresentInTheList(List<Apples> apples, String f) {
        if (apples != null) {
            for (Apples apple : apples) {
                if (f.equalsIgnoreCase(apple.getFruit())) {
                    return true;
                }
            }
        }
        return false;
    }

您可以像执行那样调用该方法。

isThisFruitHere(List<Apples> apples, APPLES)
isThisFruitHere(List<Apples> apples, ORANGES)

给定

private boolean containsType(List<Apples> apples, boolean orangeType) {
    if (apples != null) {
        for (Apples apple : apples) {
            String type = apple.getFruit();
            boolean isOrange = StringUtils.equalsIgnoreCase(type, ORANGE);
            if (orangeType == isOrange)
                return true;
        }
    }
    return false;
}

您的方法将如下所示

  • getFirst(apples) => containsType(apples, false)
  • getSecond(apples) => containsType(apples, true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM