Java addAll overload function

I wanted to convert array [] to ArrayList. In java it is easier to use

new ArrayList<Element>(Arrays.asList(array))

      

But what if I would like to do some sanity checking on the elements in the array before placing them in the ArrayList. eg,

new ArrayList<Element>(Arrays.asList(array,Sanity.isNotNull))

      

i.e. Something similar to Comparator, add an item to the ArrayList only when the function in the second argument is correct for that item.

I could always do for and add elements myself, but is there anything built into Java? Second question: is there a way to overload the addAll function to achieve the above purpose?

+3


source to share


1 answer


In Java 8, you can do something like:



new ArrayList<Element>(Arrays.asList(array).stream()
     .filter(elem -> /* condition on element that returns a boolean, i.e. "elem.age > 21" */ )
).collect(Collectors.toList());

      

+4


source







All Articles