Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
sidgate Avatar asked Jul 24 '15 11:07

sidgate


People also ask

Can we use if condition in stream in Java?

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.


1 Answers

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
        }
    }
}
like image 113
Jon Skeet Avatar answered Sep 24 '22 03:09

Jon Skeet