97

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
  • What do you mean by filter out? Do you mean create a new array without those values? Commented Jun 9, 2014 at 1:53
  • 2
    Not sure if possible with a double[], but easy with a List: dreamsyssoft.com/java-8-lambda-tutorial/filter-tutorial.php Commented Jun 9, 2014 at 1:54
  • 2
    FYI that's called a list comprehension. Generators use parens, like this: (i for i in x if i > 0) Commented Oct 4, 2016 at 11:10

2 Answers 2

151

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I think that is about as concise as Java will get :D
I think it should be double[] toArray = Arrays.stream(d).filter(x -> x > 0).toArray();
@Raj that's valid also if you want to assign the returned array to a separate reference.
I think the call to toArray() will return an Object [] instead, so that second line might fail with a cast exception. Thanks!
@JesúsZazueta I have edited the answer, does that solve your problem?
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]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.