21

I'm looking for the cleanest way to filter a list in Java-8, with a simple lambda Predicate, without creating a new list.

In particular, this solution is not suitable, as toList() returns a new List:

List<Person> beerDrinkers = persons.stream()
    .filter(p -> p.getAge() > 16)
    .collect(Collectors.toList());

Note that the following solution does not work either, because the list should be clear()ed of its original values (but obviously, if you clear it before filtering, there's nothing left to filter...):

persons.stream()
    .filter(p -> p.getAge() > 16)
    .forEach((p) -> persons.add(p));

(Also, I'd prefer a solution not involving the use of a 3rd party library or framework)

1

1 Answer 1

36
beerDrinkers.removeIf(p -> p.getAge() <= 16);
5
  • 1
    A side note: This may have a quadratic asymptotic running time (depending on the type of the list), whereas filtering and collecting will always be O(n)
    – Marco13
    Aug 1, 2015 at 12:39
  • 3
    @Marco13 It won't with ArrayList nor with LinkedList, which are by far the most commonly used lists, though. Do you have a specific List implementation in mind?
    – JB Nizet
    Aug 1, 2015 at 12:44
  • 7
    @JBNizet Apologies, I thought this would have O(n²) for an ArrayList, due to the O(n) for remove(E) on ArrayList, but in fact, there is a dedicated implementation for the removeIf in ArrayList that uses a BitSet to first find out the elements to be removed, and then compacts the elements of the ArrayList in one run. Now I consider deleting the above comment (and this one), although it would still be true for any list where remove(E) is an O(n) operation and that uses the default implementation of removeIf that is defined in the Collection interface...
    – Marco13
    Aug 1, 2015 at 12:57
  • 8
    No need to apologize. Don't delete the comment. It's useful to ask yourself such a question when dealing with a default method, and it might clear the doubts of future readers. I myself had to check the documentation (and the code) to ensure that ArrayList overrode the method.
    – JB Nizet
    Aug 1, 2015 at 12:58
  • 1
    @Marco13 I agree with JB Nizet; this is a useful discussion. It may also be worth noting that the conventional approach of using an Iterator and deleting matching elements one at a time may have O(n^2) performance, at least with an ArrayList. Aug 1, 2015 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.