How to filter strings via length using stream in java ?

How to filter strings via length using stream in java

How to filter strings via length using stream in java

In this Java code snippet, a list of strings named `words` is created, containing “apple,” “banana,” “cherry,” and “date.” Utilizing Java 8 streams, a new list called `longWords` is generated by filtering the `words` list.

The `filter` operation selects only those strings from the original list that have a length greater than 5 characters. The `collect` operation assembles the filtered strings into a new list, resulting in `longWords` containing strings that fulfill the length condition.


List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
List<String> longWords = words.stream()
.filter(s -> s.length() > 5)
.collect(Collectors.toList());

Leave a Reply

Your email address will not be published. Required fields are marked *