Site icon Java Guidance

How to extract initials using stream in java?

Stream : Extracting Initials

Stream : Extracting Initials

How to extract initials using stream in java

In this Java code snippet, a list of strings named `names` is created, containing full names like “John Doe,” “Jane Smith,” and “Alice Johnson.” Using Java 8 streams, a new list called `initials` is generated by applying a transformation to each full name in the `names` list.

The `map` operation splits each full name into individual words using the space character as a delimiter. For each word, the `map` operation then extracts the first letter using the `substring(0, 1)` method, effectively obtaining the initials.

These initials are collected and joined together using `Collectors.joining()`, creating a string of initials for each full name. Finally, the `collect` operation assembles these strings of initials into the `initials` list. This results in a list containing the initials derived from the given full names.


List<String> names = Arrays.asList("John Doe", "Jane Smith", "Alice Johnson");
List<String> initials = names.stream()
.map(n -> Arrays.stream(n.split(" ")).map(s -> s.substring(0, 1)).collect(Collectors.joining()))
.collect(Collectors.toList());

Exit mobile version