How to remove null element from int array (Java)?

Ver :

I have an int array with elements 0. I want to remove those elements and reduce the size of my array.

I read an example for String array in Removing empty element from Array(Java) and apply it to my case:

int[] in1 = {0, 0, 2, 0, 3};
int[] in1 = Arrays.stream(in1).filter(x -> x != 0).toArray(int[]::new);

Unfortunately, I receive an error:

The method toArray() in the type IntStream is not applicable for the arguments (int[]::new)

My questions are:

  1. How can I achieve my goal?
  2. Why can't I filter my int array the same way as a String array?
GBlodgett :

For a primitive int[] don't supply arguments to toArray():

in1 = Arrays.stream(in1).filter(x -> x != 0).toArray();

Also notice that you do not prefix in1 with int[] again, since you have already defined the variable in1

The reason why it doesn't work the same way as the other question is because Arrays.stream(int[]) returns an IntStream which has a version of toArray() which returns an int[].

Using

Arrays.stream(new String[]{"This","", "will", "", "", "work"})

will call Arrays.stream(T[] array), which:

Returns a sequential Stream with the specified array as its source.

Or a Stream<String>. Then using toArray() from the Stream class will be calling this version, which accepts an IntFunction, which will convert it to a specific type of Array. (The toArray() method that accepts no arguments from Stream returns an Object[])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117416&siteId=1