Removes duplicates from String will remove duplicate characters (if any) from String using Java programming language. For example, let’s say we have a string “jeejava” and we want to remove duplicates from this string. So in this string the duplicate characters are e, j, and a. Therefore after removing duplicate characters we will get the final string “jeav”.

Prerequisites

Knowledge of Java

Example Implementation

We will not only remove duplicate characters (if any) from the string but also take of removing the duplicates in O(n) time complexity. We will use here hashing to remove duplicate.

public class RemoveDuplicateFromString {

	public static void main(String[] args) {
		System.out.println(removeDuplicate("jeejava"));
	}

	private static String removeDuplicate(String str) {
		Set<String> finalStr = new LinkedHashSet<>();
		for (int i = 0; i < str.length(); i++) {
			finalStr.add(String.valueOf(str.charAt(i)));
		}

		List<String> list = new ArrayList<>(finalStr);
		return String.join("", list);
	}

}

In the above source code we have used LinkedHashSet in order to maintain the order of the characters in a string otherwise you will get the desired output but in random order.

Notice how we have used string’s join method to convert ArrayList to string.

Testing the application

Run the above code, you should see the following output in the console.

jeav

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *