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

泄露秘密 提交于 2019-12-18 11:26:54

问题


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.


回答1:


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
        }
    }
}


来源:https://stackoverflow.com/questions/31609716/replacing-if-else-within-for-loops-with-java-8-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!