Search code examples
javaif-statementcollectionsjava-8java-stream

using collection and if else statement in java in optimize way


I have a below code which is working as expected and I want to optimize it, possibly if using methods of stream.

List<List<String>> colorsList = List.of(
   List.of("red","maroon"),
   List.of("blue, skyblue"),
   List.of("pink"));

int var1 = 5;
List<String> listReturn = new ArrayList<>();

for(List<String> innerList: colorsList){
    if(var1 == 5){
        if(innerList.contains("blue")){
            listReturn.addAll(innerList);
        }
    }else if(var1 == 10){
        if(innerList.contains("pink") || innerList.contains("red")){
            listReturn.addAll(innerList);
        }
    }
  }
}

Basically I am returning a single List listReturn combining 1 or more List from original colorsList based on conditions. Is there a better and optimized way to write above?


Solution

  • You could factor out the predicate, this way you don't have to repeat the code of going over and filtering the list:

    List<List<String>> colorsList = List.of(
            List.of("red","maroon"),
            List.of("blue, skyblue"),
            List.of("pink"));
    
    int var1 = 5;
    
    // switch expression
    Predicate<List<String>> predicate = switch (var1) {
        case 5 -> innerList -> innerList.contains("blue");
        case 10 -> innerList -> innerList.contains("pink") || innerList.contains("red");
        default -> innerList -> true; // if something else than 5 or 10 accept all
    };
    
    List<String> listReturn = colorsList.stream()
                   .filter(predicate).flatMap(List::stream).toList();