Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting array of non null objects

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

like image 332
Mayday Avatar asked Jul 02 '26 00:07

Mayday


1 Answers

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();
like image 177
Mayday Avatar answered Jul 03 '26 12:07

Mayday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!