3

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

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

But what If I wanted to do some sanity check over elements in array before putting them in ArrayList. for e.g.

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

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

I could always do a for and add elements myself, but is there anything inbuilt in Java? Second Question: is there a way to overload addAll function to achieve the above mentioned goal?

Mangat Rai Modi
  • 5,397
  • 8
  • 45
  • 75
  • maybe [Guava functional idioms](https://code.google.com/p/guava-libraries/wiki/FunctionalExplained) but AFAIK no internals for that –  Oct 31 '14 at 06:51
  • @RC.I have no prior experience in Guava, so can't comment on this. Plus, we don't use Guava in our office yet. I am just wondering if this is a miss in vanilla Java version? – Mangat Rai Modi Oct 31 '14 at 06:53
  • 1
    If you want a ready-made method, then you have to use some library, like Apache Commons, Google's Guava, etc. But if you don't (cannot) use some library, then you have to implement the filter function yourself. http://stackoverflow.com/questions/122105/what-is-the-best-way-to-filter-a-java-collection – Lokesh Oct 31 '14 at 07:03
  • 1
    Keep it simple, just use a loop. http://en.wikipedia.org/wiki/KISS_principle. Having a custom addAll() is going give someone a maintenance headache in years to come. – Adam Oct 31 '14 at 07:15
  • @Adam lols!But I really believe that filtering in addAll is very useful. addAll already gives an option to add all elements, adding a filter will actually make it more useful without hurting much simplicity as shown in the accepted answer below. but yeah! if there is no library, then making one will be hard to manage and loop should suffice. – Mangat Rai Modi Oct 31 '14 at 07:23
  • I strongly believe this hurts the semantics of addAll, perhaps it should be addSome(), Java 8 already provides extensive filtering via streams. I believe the core Collections APIs should be kept as simple as possible. – Adam Oct 31 '14 at 07:30
  • @Adam yup, now we have stream no need to add filters in addAll otherwise something similar would have been required in all similar functions. – Mangat Rai Modi Oct 31 '14 at 07:34

1 Answers1

4

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());
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129