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

后端 未结 1 1372
星月不相逢
星月不相逢 2020-12-28 19:04

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

for(String str: list){
    if(someCondition(str)){
       list2.add(doSomeThing(         


        
相关标签:
1条回答
  • 2020-12-28 19:34

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题