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 typeIntStreamis not applicable for the arguments(int[]::new)
My questions are:
int array the same way as a String array?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
Streamwith 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[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With