Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like find_if in Java?

In C++, I can use find_if with a predicate to find an element in a container. Is there something like that in Java? The contains method on collections uses equals and can not be parameterized.

like image 842
fredoverflow Avatar asked Apr 05 '10 09:04

fredoverflow


2 Answers

You can use Predicate from Google Collections. Here is the tutorial and an example from it:

final Predicate<Car> expensiveCar = new Predicate<Car>() {
   public boolean apply(Car car) {
      return car.price > 50000;
   }
}

List<Car> cars = Lists.newArrayList();
cars.add(new Car("Ford Taurus", 20000));
cars.add(new Car("Tesla", 90000));
cars.add(new Car("Toyota Camry", 25000));
cars.add(new Car("McClaren F1", 600000));

final List<Car> premiumCars =
   Lists.immutableList(Iterables.filter(cars, expensiveCar));

You can also look at this thread: What is the best way to filter a Collection?

like image 79
Roman Avatar answered Sep 18 '22 20:09

Roman


You can use CollectionUtils.select from Apache Commons.

For example, the following C++ code

  bool isOdd (int i) {
    return i % 2 != 0;
  }
  ...
  vector<int> myvector;
  vector<int>::iterator it;

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);

  it = find_if (myvector.begin(), myvector.end(), isOdd);
  cout << "The first odd value is " << *it << endl;

can be written in Java as,

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
List<Integer> oddNums = (List<Integer>) CollectionUtils.select(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 != 0;
    }
  }
);
System.out.println("The first odd value is "+oddNums.get(0));

Please note that, unlike in C++ example, this would create a new list of the elements satisfying the specified predicate.

EDIT :

As Matthew Flaschen has suggested in a comment below, CollectionUtils.find is even closer to what you need. So, with find, the above code can be rewritten as:

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
Integer firstOdd = (Integer) CollectionUtils.find(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 == 1;
    }
  }
);
System.out.println("The first odd value is "+firstOdd);
like image 33
missingfaktor Avatar answered Sep 17 '22 20:09

missingfaktor