Makoto Makoto - 2 years ago 172
Java Question

Java 8 Filter Array Using Lambda

I have a

and I want to filter out (create a new array without) negative values in one line without adding
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 Source

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 = -> 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 = -> !s.isEmpty()).toArray(String[]::new);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download