user5436283
user5436283

Reputation:

Java 8 - Nested if inside a loop

So I have a list and for each item in the list I have to "do something" based on each list element.

The list consists of codes and there are a total of 5 codes. The list may contain any or all codes.

So far I've used the forEach and i've written the if conditions inside it as below -

List<Category> categories = getCategories();

categories.stream().forEach(category -> {
            if(category.equals(Category.A)) {
                // do something
            } else if(category.equals(Category.B)) {
                // do something
            } else if(category.equals(Category.C)) {
                // do something
            } else if(category.equals(Category.D)) {
                // do something
            } else if(category.equals(Category.E)) {
                // do something
            }
        });

I'm looking at refactoring this. Can someone please look at how better this can be done?

Upvotes: 2

Views: 1451

Answers (3)

araknoid
araknoid

Reputation: 3125

You can add a doSomething method to the Category class and simply call it in the .forEach.

For example:

public class Category {

    // any other methods/variable/constructors

    public void doSomething() {
        //do something
    }
}

Then you can call it like this:

categories.stream().forEach(Category::doSomething);

If the // do something has not a common behaviour, you can move the if part inside the doSomething method.

Upvotes: 1

ByeBye
ByeBye

Reputation: 6946

At first, do not use multiline lambdas and create new method (with switch):

private void doSomethingBasedOnCategory(Category category) {
    switch(category) {
        case A: // do something
                break;
        case B: // do something
                break;
        case C: // do something
                break;
        case D: // do something
                break;
        case E: // do something
                break;
    }
}

Then use it in your lambda:

getCategories()
    .stream()
    .forEach(category -> doSomethingBasedOnCategory(category);

Another way is to create static map prefilled with keys (which will be Category.X) and values (which will be functions ready to use)

Upvotes: 0

Basti
Basti

Reputation: 517

The only thing I would improve is to use a switch-statement:

switch(category){    
   case Category.A:
        // do Something
   break;
}

As mentionend by luk2302 this will only work if Category is an enum.

Upvotes: 1

Related Questions