Site icon Java Guidance

Stream : Group names by Length

Stream : Grouping Names by Length

Stream : Grouping Names by Length

Stream : Group names by Length

In this Java code snippet, we’re grouping these strings by their lengths.

The `groupingBy` collector organizes the strings into a map where the keys represent the lengths, and the values are lists of strings with the same length. The code snippet efficiently creates the `groupedByLength` map, which groups the names by their lengths.

For example, names with a length of 5 (“Alice,” “Charlie”) are grouped together, and names with a length of 3 (“Bob”) are in another group.


List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Map<Integer, List<String>> groupedByLength = names.stream()
.collect(Collectors.groupingBy(String::length));

Binary Conversion in Java: A Comprehensive Guide

Exit mobile version