使用 Lambda 的 Java 8 过滤器数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24112715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Filter Array Using Lambda
提问by Makoto
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?
我有一个double[]
,我想在一行中过滤掉(创建一个没有新数组)负值而不添加for
循环。这可以使用 Java 8 lambda 表达式吗?
In python it would be this using generators:
在 python 中,这将是使用生成器:
[i for i in x if i > 0]
Is it possible to do something similarly concise in Java 8?
是否有可能在 Java 8 中做一些类似的简洁的事情?
采纳答案by Alex
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:
是的,您可以通过DoubleStream
从数组中创建 a 、过滤掉负数并将流转换回数组来实现这一点。下面是一个例子:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
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:
如果你想过滤一个不是 an 的引用数组,Object[]
你需要使用一个toArray
方法IntFunction
来获取一个原始类型的数组作为结果:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
回答by keypoint
even simpler, adding up to String[]
,
甚至更简单,加起来String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
使用内置过滤器filter(StringUtils::isNotEmpty)
的org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
和输出:
[a, b, , c, ]
[a, b, c]