reddragon72
reddragon72

Reputation: 191

removing duplicates from an arraylist using this code but ignoring case

Ok so nothing has really struck me as a good code set to remove duplicates in an ArrayList without creating a whole new array except this code from CarlJohn. I have tried to respond but my rep points are to low.... still....

So the code is working great minus one exception, it is not ignoring the case so I still get duplicates.

ArrayList<String> lst = new ArrayList<String>();
lst.add("ABC");
lst.add("ABC");
lst.add("ABCD");
lst.add("ABCD");
lst.add("ABCE");

System.out.println("Duplicates List " + lst);

Object[] st = lst.toArray();
for (Object s : st) {
    if (lst.indexOf(s) != lst.lastIndexOf(s)) {
        lst.remove(lst.lastIndexOf(s));
    }
}

System.out.println("Distinct List "+lst);

Output is

Duplicates List [ABC, ABC, abc, ABCD, ABCD, ABCE, aBCe]
Distinct List [ABC, abc, ABCD, ABCE, aBCe]

So how do I modify this to ignore the case of the words it is checking.

Upvotes: 1

Views: 1304

Answers (2)

GIRISH RAMNANI
GIRISH RAMNANI

Reputation: 624

use compareToIgnoreCase method of the String class

Upvotes: 2

Axel
Axel

Reputation: 778

String has method toUpperCase and toLowerCase, you can make both of this strings to lowerCase and then compare them

Upvotes: 0

Related Questions