Start by using generics, and let the caller declare what type of object he wants to filter by:
static <T> void removeAllLessThan(Collection<T> collection, T t) {...}
This isn't enough, however. You need to use a Comparator<T>
to provide the ordering.
static <T> void removeAllLessThan(Collection<T> collection,
Comparator<T> comparator, T t) {...}
Then, allow the user some flexibility when working with inheritance. He has to do the equivalent of t1 < t2
, but the comparator can be of any supertype of T, and the collection can be of anything that extends T:
static <T> void removeAllLessThan(Collection<? extends T> collection,
Comparator<? super T> comparator, T t) {...}
Then, there is a mistake with the deletion process. The only mechanism that can delete from a collection while iterating over it is the Iterator
. Anything else risks a ConcurrentModificationException
.
static <T> void removeAllLessThan(Iterable<? extends T> iterable,
Comparator<? super T> comparator, T t) {
for (Iterator<? extends T> it = iterable.iterator(); it.hasNext();) {
if (comparator.compare(it.next(), t) < 0) {
it.remove();
}
}
}
Note the signature change.
Finally, this is a very specific method. You will need to write lots of nearly identical methods like removeIfGreaterThan, removeIfEqualIgnoringCase, etc. Write a generic removeIf
method, with signature
public <T> removeIf(Iterable<? extends T> iterable,
Predicate<? super T> predicate){...}
Predicate
is an interface provided by lots of libraries that has just a boolean eval
method.
c
is a collection of Objects ? – Deepak Bala Apr 17 '13 at 6:31compareTo
instead ofObject
? – user1907906 Apr 17 '13 at 6:31This does not work because Object has no compareTo method
. You need the method to take aCollection<Comparable>
. – Keppil Apr 17 '13 at 6:38