I have developed following function to get an array of not null objects:
private static Object[] getArrayNotNulls(Object... objs) {
return Arrays.stream(objs).filter(Objects::nonNull).toArray();
}
Which I am calling like this:
Object[] x = getArrayNotNulls(1,2, null, 3);
This works fine, however, I was wondering, if there is not already a java method that does the same. Something like:
Object[] y = Collections.getArrayNotNull(1,2,null,3)
or a mix, I would like to call directly the
Object[] y = Arrays.stream(1,2,null,3).filter(Objects::nonNull).toArray();
// ^^^^^^^^^^
but this does not work, since it does not accept Object... arguments
Thanks to Ben comment, his solution worked out:
Arrays.<Object> asList(1, 2, null, 3).stream().filter(Objects::nonNull).toArray();
and I also found out that it can be done little bit cleaner using:
Stream.of(1, 2, null, 3).filter(Objects::nonNull).toArray();
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