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.
if/else Logic With filter()Above we implemented the if/else logic using the Stream filter() method to separate the Integer List into two Streams, one for even integers and another for odd integers.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With