I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef
should become abcdef
and the String abcdabcd
should become abcd
Here is what I have so far:
public class test { public static void main(String[] args) { String input = new String("abbc"); String output = new String(); for (int i = 0; i < input.length(); i++) { for (int j = 0; j < output.length(); j++) { if (input.charAt(i) != output.charAt(j)) { output = output + input.charAt(i); } } } System.out.println(output); } }
What is the best way to do this?
We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method.
You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.
Convert the string to an array of char, and store it in a LinkedHashSet
. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz"; char[] chars = string.toCharArray(); Set<Character> charSet = new LinkedHashSet<Character>(); for (char c : chars) { charSet.add(c); } StringBuilder sb = new StringBuilder(); for (Character character : charSet) { sb.append(character); } System.out.println(sb.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With