Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

how to keep the unfiltered data in the collection in Java 8 Streaming API?

My Input Sequence is : [1,2,3,4,5]

Result should be : [1,12,3,14,5]

That is even numbers are incremented by 10, but odd values are left intact.

Here is what I tried:

public static List<Integer> incrementEvenNumbers(List<Integer> arrays){
        List<Integer> temp = 
          arrays.stream()
                .filter(x->x%2==0)
                .map(i -> i+10)
                .collect(Collectors.toList());
        return temp;
    }

when I call this method,

System.out.println(incrementEvenNumbers(Arrays.asList(1,2,3,4,5)));

I get [12, 14]. I am wondering how to include the values not filtered to seep in but the map should not be applied for it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a ternary operator with map, so that the function you apply is either the identity for odd values, or the one that increments the value by 10 for even values:

 List<Integer> temp = arrays.stream()
                            .map(i -> i % 2 == 0 ? i+10 : i)
                            .collect(Collectors.toList());

The problem, as you saw, is that filter will remove the elements so when a terminal operation will be called, they will be filtered by the predicate.

Note that if you don't care modifying the list in place, you can use replaceAll directly, as you are doing a mapping from a type T to T.

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.replaceAll(i -> i % 2 == 0 ? i+10 : i); //[1, 12, 3, 14, 5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...