Learn how to find distinct characters from a list of strings in Java 8 using Stream API , flatMapToInt(), mapToObj(), and Collectors.toSet().
Code Explanation (Step-by-Step)
- First, convert the list into a stream using the stream() method.
- Use flatMapToInt(String::chars) to convert all Strings into a stream of characters.
- Use mapToObj(ch -> (char) ch) to convert each integer value into a Character object.
- Use collect(Collectors.toCollection(java.util.LinkedHashSet::new))to Collect the stream elements into a LinkedHashSet , which removes duplicates and maintains insertion order.
- Finally, print the distinct characters on the console.
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class FindDistinctCharacter {
public static void main(String[] args) {
List list = Arrays.asList("java", "spring", "hibernate");
Set characters = list.stream()
.flatMapToInt(String::chars)
.mapToObj(ch -> (char) ch)
.collect(Collectors.toCollection(java.util.LinkedHashSet::new));
System.out.println("Distinct character from list of String :- " + characters);
}
}
Output :
Distinct character from list of String :- [j, a, v, s, p, r, i, n, g, h, b, e, t]
Use flatMapToInt() to Extract Characters
flatMapToInt() is used to convert multiple strings into a single stream of characters.
• Each string is processed using String::chars
• chars() returns an IntStream (ASCII/Unicode values of characters)
• flatMapToInt() flattens all character streams into one continuous stream
Difference Between Collectors.toSet() and Collectors.toCollection(LinkedHashSet::new)
Using Collectors.toSet()
Syntax : collect(Collectors.toSet())
They are removes duplicates but does not guarantee the insertion order.
Using Collectors.toCollection(LinkedHashSet::new)
Syntax : collect(Collectors.toCollection(java.util.LinkedHashSet::new))
They are removes duplicates but maintain the insertion order.
FAQ
How to find distinct characters in Java 8?
Use Stream API with chars(), mapToObj(), and Collectors.toSet().
What does flatMapToInt() do?
It converts multiple strings into a stream of characters.