Remove Duplicate Characters
Remove duplicate characters from a string, keeping first occurrences.
IntermediateTopic: Module 4: String Programs
Java Remove Duplicate Characters Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
Set<Character> set = new LinkedHashSet<>();
for (char c : s.toCharArray()) {
set.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : set) {
sb.append(c);
}
System.out.println("After removing duplicates: " + sb.toString());
sc.close();
}
}Output
Enter a string: programming After removing duplicates: progamin
Understanding Remove Duplicate Characters
We use a LinkedHashSet to preserve insertion order while removing duplicates.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.