Link to home
Start Free TrialLog in
Avatar of lasutton
lasutton

asked on

Convert a String to an Array and Back Again without Duplicates

I am looking for the best way to convert a String to an Array and Back Again without any Duplicates.

Basically I have a comma delimited string that includes names.  I want to return a string that contains a comma delimited string but without any duplicates.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try
            List unique = new ArrayList(new HashSet(new ArrayList(Arrays.asList(array))));
You will have to use
String[] split(String regex)
method in String class and then remove duplicates manualy.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lasutton
lasutton

ASKER

And to move the list back into a delimited string, do I need to loop through each element and add to the new String?
For the...

array = (String[])new ArrayList<String>(new LinkedHashSet<String>(new ArrayList<String>(Arrays.asList(array)))).toArray(new String[0]);

...solution, I then parse through the array and move it into a String manually, or is there something that can do the whole thing in a single line?
>>...solution, I then parse through the array and move it into a String manually, or is there something that can do the whole thing in a single line?

Yes, you do. Unfortunately there's no 'join' method in Java
Thanks CEHJ, this works perfectly based on your help:

public String removeRepeatingElementsInDelimitedString(String aStringToParse) throws Exception {
      String[] originalList = aStringToParse.split(",");
      String noduplicatesListDelimitedResult = "";
      originalList = (String[])new ArrayList<String>(new LinkedHashSet<String>(new ArrayList<String>(Arrays.asList(originalList)))).toArray(new String[0]);
      int newListLength = originalList.length;
      for(int x = 0;x<newListLength;x++)
      {
      noduplicatesListDelimitedResult = noduplicatesListDelimitedResult + originalList[x] + ",";
      }
      noduplicatesListDelimitedResult = noduplicatesListDelimitedResult.substring(0, noduplicatesListDelimitedResult.length()-1);
            
      return noduplicatesListDelimitedResult;
}
Good - it would be better to append using a StringBuilder though