Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from a String in Java

Tags:

java

string

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?

like image 391
Ricco Avatar asked Feb 14 '11 05:02

Ricco


People also ask

How do you remove duplicates in a string in Java?

We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method.

How do I remove duplicates from a string in Java 8?

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.


1 Answers

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()); 
like image 148
Dave Avatar answered Sep 20 '22 01:09

Dave