0

I need to write a method that returns a view of a List(java.util.List). The returned view should contain only those elements in the input List that returns true when tested with the isSuccessful() method.

List<Entity> getSuccessfulEntities(List<Entity> entities)
{
  //Return a List view of entities, each element of which returns true for isSuccessful(entity)
}

I have looked at Collections and List API but couldn't find any facility for this. Any out of box thought?

Jagat
  • 1,392
  • 2
  • 15
  • 25

2 Answers2

1

There's nothing (at least that I know of) in the Java standard library, but you could use com.google.common.collect.Collections2.filter() and Predicate, which is just defined as:

public interface Predicate<T> { boolean apply(T input); }

Changes to the unfiltered and filtered Collection affect one another. Sample code:

Predicate<Entity> isSuccessful = new Predicate<Entity>() {
    public boolean apply(Entity e) {
        return e.isSuccessful();
    }
};

Collection<Entity> successfulEntities = filter(entities, isSuccessful);

Related: Java: What is the best way to filter a Collection?

Community
  • 1
  • 1
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • This creates an entirely new ArrayList. I only want a view(unmodifiable) that actually makes use of the original List. – Jagat Aug 09 '10 at 13:42
1

The generic way would be to define a Predicate interface that tests an instance of T and returns a boolean.

Then take an instance of an implementation of Predicate as a parameter to getSuccesfulEntities and iterate over the collection, calling a method on the predicate to determine if it should be in the returned collection.

pauljwilliams
  • 19,079
  • 3
  • 51
  • 79