sidgate sidgate - 2 months ago 9
Java Question

Replacing if-else within 'for' loops with Java-8 Streams

I have following simple code that I am trying to convert to functional style

for(String str: list){
if(someCondition(str)){
list2.add(doSomeThing(str));
}
else{
list2.add(doSomethingElse(str));
}
}


Is it easily possible to replace this loop with stream? Only option I see is to iterate over the stream twice with two different filter conditions.

Answer

It sounds like you can just use map with a condition:

List<String> list2 = list
    .stream()
    .map(str -> someCondition(str) ? doSomething(str) : doSomethingElse(str))
    .collect(Collectors.toList());

Short but complete example mapping short strings to lower case and long ones to upper case:

import java.util.*;
import java.util.stream.*;

public class Test {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("abC", "Long Mixed", "SHORT");
        List<String> list2 = list
            .stream()
            .map(str -> str.length() > 5 ? str.toUpperCase() : str.toLowerCase())
            .collect(Collectors.toList());
        for (String result : list2) {
            System.out.println(result); // abc, LONG MIXED, short
        }
    }
}