如何在Java 8 Streaming API中保留集合中未过滤的数据? [英] how to keep the unfiltered data in the collection in Java 8 Streaming API?

查看:131
本文介绍了如何在Java 8 Streaming API中保留集合中未过滤的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入序列是: [1,2,3,4,5]

结果应该是: [1,12,3,14,5]

这是偶数增加10,但是奇数值保持不变。

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

这是我试过的:

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

当我调用此方法时,

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

我得到 [12,14] 。我想知道如何将不是过滤的值包括在内,但不应该为它应用 map

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.

推荐答案

您可以使用带有 map 的三元运算符,以便该函数您应用的是奇数值的标识,或者对于偶数值将值递增10的标识:

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.

请注意,如果您不在乎修改列表,可以使用 replaceAll 直接,因为你正在进行从类型T到T的映射。

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]

这篇关于如何在Java 8 Streaming API中保留集合中未过滤的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆