How can you filter a collection using Streams in Java 8?

Filtering a collection with Java 8 Streams involves calling stream() on the collection, applying filter() with a Predicate describing the condition to keep, and then collecting the matching elements back into a new collection.

Key Points: • The original collection is untouched — filter() produces a new stream, and collect() produces a new collection. • filter() can be chained multiple times, or combined with Predicate.and()/or() to express compound conditions. • collect(Collectors.toList()), toSet(), or toMap() determines what kind of collection the filtered elements end up in. • For simple in-place removal on a mutable collection, removeIf(Predicate) is often more efficient than filtering and reassigning. • Filtering large collections with a parallelStream() can speed up expensive predicate checks on multicore hardware.

Example: Given a List<Order>, orders.stream().filter(o -> o.getTotal() > 100).collect(Collectors.toList()) extracts only the orders whose total exceeds 100 into a brand-new list.

Code Example:

List<String> words = Arrays.asList("cat", "elephant", "dog", "giraffe");

List<String> longWords = words.stream()
        .filter(w -> w.length() > 3)
        .collect(Collectors.toList());

System.out.println(longWords); // [elephant, giraffe]

Interview Tip: A concise interview answer is:

"I call stream() on the collection, apply filter() with a Predicate describing what to keep, and collect the results into a new collection with collect(Collectors.toList()) or similar. It's a non-destructive way to derive a subset — the original collection is never modified — and if I just need to remove matching elements in place, removeIf() is the more direct choice."