user4479371
user4479371

Reputation:

How to combine two methods in JAVA?

I have two methods which returns two values. The method is mostly same so I was thinking to combine them to single method and manipulate to return different values but not sure will it be useful?

Can someone tell me is this method can be converted to single ?

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;
    }

Upvotes: 0

Views: 4185

Answers (3)

zapl
zapl

Reputation: 63955

Given

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;
}

Your methods would be equivalent as follows

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

Upvotes: 0

Jorn Vernee
Jorn Vernee

Reputation: 33865

You can use streams for this:

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));

Upvotes: 4

Yes you can for sure merge those methods into a new one that can be more generic for what it does...

for example, if I rename the method to isThisFruitPresentInTheList please forgive the name convention I use :) ...

Then you can pass a list to the method, and as a 2nd parameter the fruit you are looking for, the method will return true if a fruit is present in the list, false otherwise...

Example:

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

and you can invoke the method like doing....

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

Upvotes: 1

Related Questions