Removing first case insensitive duplicate of an ArrayList

user9303958 :

I have an arraylist containing some strings:

ArrayList<String> strList = new ArrayList<String>();
strList.addAll(Arrays.asList("interface", "list", "Primitive", "class", "primitive", "List", "Interface", "lIst", "Primitive"));

I have wrote a method to remove the case insensitive strings of the arraylist:

public static ArrayList<String> removeDuplicates(ArrayList<String> strList) {

    for(int i = 0; i < strList.size(); i++) {
        for(int j = i + 1; j < strList.size(); j++) {
            if(strList.get(i).equalsIgnoreCase(strList.get(j))){
                strList.remove(j);
                j--;
            }
        }
    }
    return strList;   
}

Ouput:

[interface, list, Primitive, class]

However, I am trying to remove just the first occurance of the strings. I am trying to make it so my output would equal:

[Interface, lIst, Primitive, class]

Which would be the last occurrences of the duplicates in the arraylist

What I'm trying to do specifically:

The version of the string that remains is the same as the last occurrence. In other words, the version of the last occurrence stays at the location of the first occurrence

oleg.cherednik :

I think that remove from the ArrayList is not good idea. It is better using Map to create new list:

public static List<String> removeDuplicates(List<String> strList) {
    Map<String, String> map = new LinkedHashMap<>();
    strList.forEach(item -> map.put(item.toLowerCase(), item));
    return new ArrayList<>(map.values());
}

Input: [interface, list, Primitive, class, primitive, List, Interface, lIst, Primitive]

Output: [Interface, lIst, Primitive, class]

P.S.

Same with one line Stream, but a bit not so clear:

public static List<String> removeDuplicates(List<String> strList) {
    return new ArrayList<>(strList.stream().collect(Collectors.toMap(String::toLowerCase, str -> str, (prev, next) -> next, LinkedHashMap::new)).values());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83198&siteId=1