Java – Unique characters in String

To get the unique characters in a string in Java, you can iterate over the characters in a string using a For loop, and maintain the unique characters in a set using a HashSet.

In this tutorial, we will learn how to use a For loop and a HashSet to get the unique characters in a string in Java, with examples.

1. Get unique characters in String using HashSet in Java

Steps to get unique characters in a string using HashSet.

  1. Given a string in str.
  2. Initialize an empty HashSet uniqueChars.
  3. Iterate over the characters of string using a For loop.
    1. Add character to the set uniqueChars.
  4. You have all the unique characters in the given string collected into uniqueChars set. You may print these unique characters.

Now, let us write a Java program, to get the unique characters of a string "Hello World" and print them to output.

Java Program

</>
Copy
import java.util.HashSet;
import java.util.Set;

public class Main {
	public static void main(String[] args) {
		String str = "HelloWorld";
        Set<Character> uniqueCharacters = new HashSet<>();
        
        // Get unique characters in the string
		for(char ch: str.toCharArray()) {
			uniqueCharacters.add(ch);
		}
		
		// Print the unique characters
		for(char ch: uniqueCharacters) {
			System.out.println(ch);
		}
	}
}

Output

r
d
e
W
H
l
o

Conclusion

In this Java String tutorial, we have seen how to get the unique characters in a string in Java using a For loop and HashSet, with examples.