Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments