Learnitweb

Filter a List of Strings Based on Length

Approach 1: Using filter()

List<String> words = Arrays.asList("a","abcd","xyz","hello");
List<String> longOnes = words.stream()
                             .filter(s -> s.length() >= 3)
                             .collect(Collectors.toList());
System.out.println(longOnes); // [abcd, xyz, hello]

Why it works:

  • Standard predicate-based filtering.

Approach 2: Using Collectors.filtering() (Alternative)

List<String> longOnes = words.stream()
                             .collect(Collectors.filtering(s -> s.length() >= 3, Collectors.toList()));
System.out.println(longOnes); // [abcd, xyz, hello]

Why it works:

  • Shows collector-based filtering, useful in downstream collection chains.