1

Hello I'd like to add Strings to an ArrayList and then sort it to remove duplicates. The order should remain the same way I added those Strings though. What I want: [randomtext, testtext, anothertext] What I get: [anothertext, randomtext, testtext]

Is this possible or is there an easier way?

    ArrayList<String> abc = new ArrayList();

    abc.add("randomtext");
    abc.add("testtext");
    abc.add("anothertext");
    abc.add("randomtext");
    abc.add("testtext");
    abc.add("anothertext");
    abc.add("randomtext");
    abc.add("testtext");
    abc.add("anothertext");

    Collections.sort(abc);      
    for (int i = 1; i < abc.size() ; i++) 
    {
        if(abc.get(i) == abc.get(i-1))
        {
            abc.remove(i);
            i -= 1;
        }
    }
    System.out.print(abc);
1
  • 1
    So you're actually asking how to sort the array list not in place? Commented May 26, 2015 at 11:51

2 Answers 2

2

The best way is to ensure you don't add duplicates whenever you add something to the list.

if(!myList.contains(item)){
  myList.add(item);
}

If you are receiving a List from outside the scope of your method/class, then the easiest may be adding the contents to a LinkedHashSet to eliminate duplicates and then getting them back out. LinkedHashSet maintains order.

LinkedHashSet<String> set = new LinkedHashSet<>();
set.addAll(myList); // assuming myList is List<String>
myList.clear();
myList.addAll(set);

EDIT: My answer is based on your statements (bold by me for emphasis)

Hello I'd like to add Strings to an ArrayList and then sort it to remove duplicates. The order should remain the same way I added those Strings though.

So you're only sorting to remove duplicates. My answer avoids the sort and puts the burden on LinkedHashSet.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this (convert your List into LinkedHashSet)

 Set<String> a = new LinkedHashSet<String>(abc);
 System.out.println(a);

1 Comment

why -1 to this answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.