Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

In Java programming, printing distinct characters from a string is a fundamental task often required in text processing and analysis.

In this tutorial, we’ll explore various approaches to handling and processing unique characters.

2. Using Set Collection

One effective way to print distinct characters from a string is by utilizing a Set collection in Java. A Set automatically handles duplicates, allowing us to collect unique characters efficiently. Here’s how you can implement this method:

String inputString = "BBaaeelldduunngg";

@Test
public void givenString_whenUsingSet_thenFindDistinctCharacters() {
    Set<Character> distinctChars = new HashSet<>();
    for (char ch : inputString.toCharArray()) {
        distinctChars.add(ch);
    }
    assertEquals(Set.of('B', 'a', 'e', 'l', 'd', 'u', 'n', 'g'), distinctChars);
}

In this approach, we first iterate over each character of the input string named inputString. It adds each character to a HashSet named distinctChars, which automatically eliminates duplicates due to the properties of a Set.

Finally, we verify that the distinct characters collected match the expected set of unique characters using the assertEquals() method.

3. Using Java Streams

Another approach to obtaining distinct characters is by leveraging Java Streams. Streams provide a concise and functional way to work with collections, including extracting distinct elements. Here’s an example:

@Test
public void givenString_whenUsingStreams_thenFindDistinctCharacters() {
    Set<Character> distinctChars = inputString.chars()
      .mapToObj(c -> (char) c)
      .collect(Collectors.toSet());
    assertEquals(Set.of('B', 'a', 'e', 'l', 'd', 'u', 'n', 'g'), distinctChars);
}

Here, we convert the input string inputString into an IntStream of character values using the inputString.chars() method. Then, we map back each character value to its corresponding char value using the mapToObj(c -> (char) c).

Moreover, we utilize the Collectors.toSet() terminal operation to collect these characters into a Set<Character> that automatically ensures that duplicates are eliminated due to the properties of a Set.

4. Using LinkedHashMap

We can use a LinkedHashMap as an efficient way to maintain unique characters in a string. Here’s an example of this approach:

@Test
public void givenString_whenUsingLinkedHashMap_thenFindDistinctCharacters() {
    Map<Character, Integer> charCount = new LinkedHashMap<>();
    for (char ch : inputString.toCharArray()) {
        charCount.put(ch, 1);
    }
    assertEquals("[B, a, e, l, d, u, n, g]", charCount.keySet().toString());
}

In this method, we iterate over each character and use the charCount.put(ch, 1) method to add it to the LinkedHashMap. Furthermore, the value 1 associated with each character isn’t important for this use case; it’s just a placeholder to occupy the map.

It is noteworthy that the LinkedHashMap maintains the order of insertion, so as we iterate through the string, characters are added in the order they first appear.

5. Conclusion

In conclusion, printing distinct characters from a string in Java can be accomplished using various methods, including Set collections, Java Streams, and LinkedHashMap. Each approach offers unique advantages, depending on the specific requirements of our application.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW