12. Removing duplicate characters

Let's start with a solution to this problem that relies on StringBuilder. Mainly, the solution should loop the characters of the given string and construct a new string containing unique characters (it is not possible to simply remove characters from the given string since, in Java, a string is immutable).

The StringBuilder class exposes a method named indexOf(), which returns the index within the given string of the first occurrence of the specified substring (in our case, the specified character). So, a potential solution to this problem would be to loop the characters of the given string and add them one by one in StringBuilder every time the indexOf() method that's applied to the current character returns -1 (this negative means that StringBuilder doesn't contain the current character):

public static String removeDuplicates(String str) {

char[] chArray = str.toCharArray(); // or, use charAt(i)
StringBuilder sb = new StringBuilder();

for (char ch : chArray) {
if (sb.indexOf(String.valueOf(ch)) == -1) {
sb.append(ch);
}
}
return sb.toString();
}

The next solution relies on a collaboration between HashSet and StringBuilder. Mainly, HashSet ensures that duplicates are eliminated, while StringBuilder stores the resulting string. If HashSet.add() returns true, then we add the character in StringBuilder as well:

public static String removeDuplicates(String str) {

char[] chArray = str.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> chHashSet = new HashSet<>();

for (char c: chArray) {
if (chHashSet.add(c)) {
sb.append(c);
}
}
return sb.toString();
}

The solutions we've presented so far use the toCharArray() method to convert the given string into char[]. Alternatively, both solutions can use str.charAt(position) as well.

The third solution relies on Java 8 functional style:

public static String removeDuplicates(String str) {

return Arrays.asList(str.split("")).stream()
.distinct()
.collect(Collectors.joining());
}

First, the solution converts the given string into Stream<String>, where each entry is actually a single character. Furthermore, the solution applies the stateful intermediate operation, distinct(). This operation will eliminate duplicates from the stream, so it returns a stream without duplicates. Finally, the solution calls the collect() terminal operation and relies on Collectors.joining(), which simply concatenates the characters into a string in the encounter order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.66.185