问题描述
我有一个 double[]
并且我想在一行中过滤掉(创建一个没有新数组)负值而不添加 for
循环.这可以使用 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]
如果要过滤不是 Object[]
的引用数组,则需要使用 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 过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!