用 Java-8 Streams 替换“for”循环中的 if-else

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31609716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:18:59  来源:igfitidea点击:

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

javafunctional-programmingjava-8

提问by sidgate

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.

是否可以轻松地用流替换此循环?我看到的唯一选择是使用两种不同的过滤条件对流进行两次迭代。

采纳答案by Jon Skeet

It sounds like you can just use mapwith a condition:

听起来你可以只使用map一个条件:

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