使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:13:14  来源:igfitidea点击:

Java 8 Filter Array Using Lambda

javalambdajava-8

提问by Makoto

I have a double[]and I want to filter out (create a new array without) negative values in one line without adding forloops. 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 DoubleStreamfrom 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 toArraymethod which takes an IntFunctionto 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]