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?
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?
even simpler, adding up to
String[]
,use built-in filter
filter(StringUtils::isNotEmpty)
oforg.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
and output:
[a, b, , c, ] [a, b, c]
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:If you want to filter a reference array that is not an
Object[]
you will need to use thetoArray
method which takes anIntFunction
to get an array of the original type as the result: