-1

I have code like this

int[] array = {1, -1, 2, 3, -4};

Integer[] out = Arrays
    .stream(array)
    .filter(elem -> elem >= 0) // remove negatives
    .boxed()
    .collect(Collectors.toList())
    .toArray(new Integer[array.length]);

But the filter operation leaves the negative elements in the array as nulls. Why doesn't it remove them?

Bluefire
  • 13,519
  • 24
  • 74
  • 118
  • seems like you've been mixing `int` with `Integer` mostly -> http://stackoverflow.com/questions/42685825/arraystoreexception-thrown-when-converting-hashset-to-array – Naman Mar 09 '17 at 03:48

1 Answers1

5

Your out array is the same length as array array.

Do either this:

int[] out = Arrays
        .stream(array)
        .filter(elem -> elem >= 0) // remove negatives
        .toArray();

or do this:

Integer[] out = Arrays
        .stream(array)
        .filter(elem -> elem >= 0) // remove negatives
        .boxed()
        .toArray(Integer[]::new);
Nick Ziebert
  • 1,258
  • 1
  • 9
  • 17