Remove Duplicates from String using Java

Introduction

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 roytuts and we want to remove duplicates from this string. So in this string the duplicate character is t. Therefore after removing duplicate characters we will get the final string roytus.

Prerequisites

Knowledge of Java

We will remove duplicate characters from a string using various ways. Here I am showing different ways to remove duplicate characters in the following examples.

Using HashSet

Using Set we will remove duplicate characters (if any) from the string in O(n) time complexity. We will use here hashing technique to remove duplicate.

In this example order is not maintained. We will see next example how to maintain order.

private static String removeDuplicateUsingHashSet(String str) {
	Set<String> finalStr = new HashSet<>();

	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);
}

Using LinkedHashSet

In the below 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.

The time complexity will be same as the previous example O(n).

private static String removeDuplicateUsingLinkedHashSet(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);
}

Using Distinct

We will use Java 8’s distinct() method to eliminate duplicates from string.

The time complexity is O(n).

private static String removeDuplicateUsingDistinct(String str) {
	StringBuilder sb = new StringBuilder();
	// StringBuffer sb = new StringBuffer();

	str.chars().distinct().forEach(c -> sb.append((char) c));

	return sb.toString();
}

Using Sorting

We will use sorting technique to eliminate duplicates from string. First we will convert string to character array. Then using Arrays.sort() method we will sort the character array. next we will iterate and eliminate the duplicate character. Order of the characters in output string is not maintained.

Time complexity is O(n log n).

private static String removeDuplicateUsingSorting(String str) {
	StringBuilder sb = new StringBuilder();
	// StringBuffer sb = new StringBuffer();

	char[] chars = str.toCharArray();

	Arrays.sort(chars);

	sb.append(chars[0]);

	for (int i = 1; i < chars.length; i++) {
		if (chars[i] != chars[i - 1]) {
			sb.append(chars[i]);
		}
	}

	return sb.toString();
}

Using indexOf() of String

We can also eliminate duplicate characters from string using String’s indexOf() method. Time complexity is O(n^2). Order of the characters in output string is not maintained.

private static String removeDuplicateUsingIndexOf(String str) {
	StringBuilder sb = new StringBuilder();
	// StringBuffer sb = new StringBuffer();

	for (int i = 0; i < str.length(); i++) {
		char ch = str.charAt(i);
		int anotherIndexOfCh = str.indexOf(ch, i + 1);
		if (anotherIndexOfCh == -1) {
			sb.append(ch);
		}
	}

	return sb.toString();
}

Using Character Array

We will convert string to character array and iterate through each character to check equality with the previous character. We will use here nested for loop. Time complexity is O(n^2). Order of the characters in output string is not maintained.

private static String removeDuplicateUsingCharArray(String str) {
	StringBuilder sb = new StringBuilder();
	// StringBuffer sb = new StringBuffer();

	char[] chars = str.toCharArray();

	for (int i = 0; i < chars.length; i++) {
		boolean repeatedCharFound = false;

		for (int j = i + 1; j < chars.length; j++) {
			if (chars[i] == chars[j]) {
				repeatedCharFound = true;
				break;
			}
		}

		if (!repeatedCharFound) {
			sb.append(chars[i]);
		}
	}

	return sb.toString();
}

Create Main Method

Create main method in a Java class to test the above examples.

public static void main(String[] args) {
	System.out.println(removeDuplicateUsingHashSet("roytuts"));
	System.out.println(removeDuplicateUsingLinkedHashSet("roytuts"));
	System.out.println(removeDuplicateUsingDistinct("roytuts"));
	System.out.println(removeDuplicateUsingSorting("roytuts"));
	System.out.println(removeDuplicateUsingIndexOf("roytuts"));
	System.out.println(removeDuplicateUsingCharArray("roytuts"));
}

Testing the Application

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

rstuyo
roytus
roytus
orstuy
royuts
royuts

Source Code

Download

Thanks for reading.

Related posts

Leave a Comment