In Java, there are multiple ways to print distinct characters from a string. This article will explore three approaches: using Sets, Java Streams, and LinkedHashMap. Each method has its own advantages and is suitable for different use cases.
1. Using Sets
The Set interface in Java is a collection that does not allow duplicate elements. This method iterates through the string, adding each character to a HashSet. Since HashSet doesnβt allow duplicates, only the distinct characters will be retained. Here is an example of how you can use it:
DistinctCharactersUsingSet.java
public class DistinctCharactersUsingSet {
public static void main(String[] args) {
String input = "javacodegeeks";
printDistinctCharsUsingSet(input);
}
public static void printDistinctCharsUsingSet(String str) {
Set<Character> distinctChars = new HashSet<>();
for (char ch : str.toCharArray()) {
distinctChars.add(ch);
}
System.out.println(" " + distinctChars);
}
}
First, It creates a HashSet named distinctChars to store the distinct characters. A loop iterates through each character ch in the string converted to a character array using toCharArray(). Inside the loop, ch is added to the distinctChars set. If the character already exists, adding it again will have no effect since sets donβt allow duplicates. Finally, the distinctChars set containing the unique characters is printed.
Output from running the Java code above is:
[a, c, s, d, e, v, g, j, k, o]
2. Using Streams
Java Streams API provides a functional approach to processing sequences of elements. Streams can be used to filter out duplicate characters and print the distinct ones.
DistinctCharactersUsingStreams.java
public class DistinctCharacterUsingStreams {
public static void main(String[] args) {
String input = "jacavodegeeks";
printDistinctCharacters(input);
}
public static void printDistinctCharacters(String str) {
str.chars()
.distinct()
.mapToObj(ch -> (char) ch)
.forEach(ch -> System.out.print(ch + " "));
}
}
In this example, The chars() method converts the string into an IntStream of characters. The distinct() method filters out duplicate characters and the mapToObj(ch -> (char) ch) converts the IntStream back to a character stream (Stream<Character>). We use forEach to print each character.
3. Using LinkedHashMap (Preserving Order)
If you need to preserve the order of distinct characters in which they appear in the original string, you can use a LinkedHashMap. The insertion order is maintained, and duplicate insertions are ignored. Here is an example:
DistinctCharactersUsingLinkedHashMap.java
public class DistinctCharactersUsingLinkedHashMap {
public static void main(String[] args) {
String input = "javacodegeeks";
printUniqueCharacters(input);
}
public static void printUniqueCharacters(String str) {
Map<Character, Boolean> charMap = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
charMap.putIfAbsent(ch, true);
}
System.out.println(" " + charMap.keySet());
}
}
In this approach, we create a LinkedHashMap to store characters. Next, we convert the string to a character array and iterate through each character and use putIfAbsent to add each character to the map if itβs not already present. Finally, we iterate over the keys of the map to print each unique character.
The output is:
4. Conclusion
In this article, we explored three methods to print distinct characters from a string in Java with each method having its unique advantages:
- Using Set Collection is straightforward, ensuring uniqueness with minimal code.
- Using Java Streams is functional and elegant, leveraging the power of Java 8 Streams.
- Using LinkedHashMap maintains the insertion order.
5. Download the Source Code
This was an article on how to print unique Characters from a String in Java.
You can download the full source code of this example here: Print Unique Characters from a String in Java
Thank you!
We will contact you soon.
Omozegie AziegbeJune 10th, 2024Last Updated: June 10th, 2024

This site uses Akismet to reduce spam. Learn how your comment data is processed.