Makoto Makoto - 6 months ago 27
Java Question

Java 8 Filter Array Using 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 lamdba expressions?

In python it would be this using generators:

[i for i in x if i > 0]


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

Answer

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