Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java 1.5 equivalent to the Predicate<T> methods in .Net?

Specifically, I'm looking for similarly clean notation to the Collection<T>.TrueForAll / Exists, etc.

It feels smelly to have to write a foreach loop to inspect the return of a method on each object, so I'm hoping there's a better Java idiom for it.

like image 515
Tetsujin no Oni Avatar asked Apr 24 '09 20:04

Tetsujin no Oni


2 Answers

Predicates are provided in the Google Collections library.

like image 65
erickson Avatar answered Nov 17 '22 01:11

erickson


Functional Java provides first-class functions. A predicate is expressed as F<T, Boolean>. For example, here's a program that tests an array for the existence of a string that is all lowercase letters.

import fj.F;  
import fj.data.Array;  
import static fj.data.Array.array;
import static fj.function.Strings.matches;

public final class List_exists {  
  public static void main(final String[] args) { 
    final Array<String> a = array("Hello", "There", "how", "ARE", "yOU?");  
    final boolean b = a.exists(matches.f("^[a-z]*$"));  
    System.out.println(b); // true
  }  
}
like image 6
Apocalisp Avatar answered Nov 17 '22 01:11

Apocalisp