使用Lambda的Java 8过滤器阵列 [英] Java 8 Filter Array Using Lambda

查看:105
本文介绍了使用Lambda的Java 8过滤器阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 double [] 我希望在一行中过滤掉(创建一个没有新的数组)负值,而不是为< c>添加 / code>循环。这是否可以使用Java 8 lambda表达式?

I have a double[] and I want to filter out (create a new array without) negative values in one line without adding for loops. Is this possible using Java 8 lambda expressions?

在python中,这将使用生成器:

In python it would be this using generators:

[i for i in x if i > 0]

是否有可能在Java 8中做同样简洁的事情?

Is it possible to do something similarly concise in Java 8?

推荐答案

是的,你可以通过从数组中创建一个 DoubleStream 来做到这一点,过滤掉底片,并将流转换回数组。以下是一个示例:

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

如果要过滤不是<$的参考数组c $ c>对象[] 您将需要使用 toArray 方法,它采用 IntFunction 得到一个原始类型的数组作为结果:

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

这篇关于使用Lambda的Java 8过滤器阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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