Java 8 Filter Array Using Lambda

JavaLambdaJava 8

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMakotoView Question on Stackoverflow
Solution 1 - JavaAlex - GlassEditor.comView Answer on Stackoverflow
Solution 2 - JavakeypointView Answer on Stackoverflow