Search code examples
javajava-8refactoringoption-typeunderscore-java

how to convert else if in java8


How to change the below code to remove if-else and use Java8

List<String> list1;
List<String> list2;
List<String> list3;
String str;
if(list1.contains(str)){
    event.getMessage().setInvocationProperty("ABC","ABC1");
}
else if(list2.contains(str)){
    event.getMessage().setInvocationProperty("ABC2","ABC3");
}
else if(list3.contains(str)){
    event.getMessage().setInvocationProperty("ABC4","ABC5");
}

Solution

  • It is possible to do it without if-else, but for this case, if-else would still be better than using streams.

    List<String> list1;
    List<String> list2;
    List<String> list3;
    String str;
    Map<List<String>, List<Param>> paramMap = new HashMap<>();
    paramMap.put(list1,List.of(ABC,ABC1));
    paramMap.put(list2,List.of(ABC2,ABC3));
    paramMap.put(list3,List.of(ABC4,ABC5));
    
    List.of(list1,list2,list3)
        .stream()
        .filter(list -> list.contains(str))
        .findFirst()
        .ifPresent(list -> event.getMessage().setInvocationProperty(paramMap.get(list).get(0),paramMap.get(list).get(1)));
    

    Another solution without using the list as key in paramMap:

    Map<Integer, List<Param>> paramMap = new HashMap<>();
    paramMap.put(1,List.of(ABC,ABC1));
    paramMap.put(2,List.of(ABC2,ABC3));
    paramMap.put(3,List.of(ABC4,ABC5));
    List<List<String>> lists = List.of(list1,list2,list3);
    List<String> mList = lists.stream()
                              .filter(list -> list.contains(str))
                              .findFirst()
                              .ifPresent(list -> {
        Integer index = Integer.valueOf(lists.indexOf(list));     
        event.getMessage()
             .setInvocationProperty(paramMap.get(index).get(0),paramMap.get(index).get(1))
        });