96

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?

3

2 Answers 2

149

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);
5
  • 5
    I think that is about as concise as Java will get :D
    – Makoto
    Commented Jun 9, 2014 at 2:12
  • I think it should be double[] toArray = Arrays.stream(d).filter(x -> x > 0).toArray();
    – Raj
    Commented Jun 9, 2014 at 2:24
  • @Raj that's valid also if you want to assign the returned array to a separate reference. Commented Jun 9, 2014 at 2:27
  • 6
    I think the call to toArray() will return an Object [] instead, so that second line might fail with a cast exception. Thanks! Commented May 17, 2016 at 16:37
  • 1
    @JesúsZazueta I have edited the answer, does that solve your problem? Commented May 17, 2016 at 16:48
3

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.