Core Java

Print Distinct Characters from a String in Java

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:

Figure 1: Result of Using LinkedHashMap to Print Unique Characters from a String in Java
Figure 1: Result of Using LinkedHashMap to Print Unique Characters from a String in Java

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.

Download
You can download the full source code of this example here: Print Unique Characters from a String in Java

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button