使用 Lambda 的 Java8过滤器数组

我有一个 double[],我想过滤掉(创建一个新的数组没有)负值在一行没有添加 for循环。这可以使用 Java8的 lambda 表达式吗?

在 python 中,它使用生成器:

[i for i in x if i > 0]

有可能在 Java8中做一些类似的简洁的事情吗?

153275 次浏览

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]

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

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

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]