Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java oneliner for list cleanup

Is there a construct in java that does something like this(here implemented in python):

[] = [item for item in oldList if item.getInt() > 5]

Today I'm using something like:

ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
    if( item.getInt > 5) {
     newList.add(item);
    }
}

And to me the first way looks a bit smarter.

like image 619
Simon Lenz Avatar asked Sep 21 '10 12:09

Simon Lenz


2 Answers

Java 7 might or might not implement closures and hence support functionality like this, but currently it doesn't, so on the Java VM you have the options to do it in Groovy, Scala or Clojure (possible others, too), but in java you can only get close to that by using helpers like Guava's Collections2.filter().

JDK 7 sample code:

findItemsLargerThan(List<Integer> l, int what){
   return filter(boolean(Integer x) { x > what }, l);
}  
findItemsLargerThan(Arrays.asList(1,2,5,6,9), 5)

Groovy sample code:

Arrays.asList(1,2,5,6,9).findAll{ it > 5}

Guava Sample Code:

Collections2.filter(Arrays.asList(1, 2, 5, 6, 9),
    new Predicate<Integer>(){
        @Override
        public boolean apply(final Integer input){
            return input.intValue() > 5;
        }
    }
);

Scala sample code (thanks Bolo):

Array(1, 2, 5, 6, 9) filter (x => x > 5)
like image 126
Sean Patrick Floyd Avatar answered Oct 05 '22 13:10

Sean Patrick Floyd


You can give a look at lambdaj. There is a select method you can use with a hamcrest condition.

like image 45
Colin Hebert Avatar answered Oct 05 '22 11:10

Colin Hebert