Question

An exercise from the Java tutorial on Java Collections Framework requires that a SortedSet be used to eliminate duplicates of the arguments and a Comparator be specified so that case is ignored when sorting and identifying set elements.

Here is the exact requirement: "Take the FindDupsexample and modify it to use a SortedSet instead of a Set. Specify a Comparator so that case is ignored when sorting and identifying set elements."

And here is the FindDupsExample:

import java.util.*;
public class FindDups {
public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    for (String a : args)
           s.add(a);
           System.out.println(s.size() + " distinct words: " + s);
}
}

The most I could come up with to achieve the desired behavior (eliminating duplicates by considering a word written once with small caps and another time with big caps as being a duplicate) is the below code, BUT I am clueless on how to use the Comparator and the SortedSet. I am using the SortedSet in my example, but I could very well use a simple Set:

public class FindDups {
public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    List<String> list = new ArrayList<String>();
    SortedSet<String> eliminatedDups = null;

    for (String a : args) {
           s.add(a);
           list.add(a.toLowerCase());
    }
    eliminatedDups = new TreeSet<String>(list);

    System.out.println(s.size() + " distinct words by taking into consideration the case: " + s);
    System.out.println(list.size() + " initial list translated into all small caps: " + list);
    System.out.println(eliminatedDups.size() + " distinct words by ignoring case: " + eliminatedDups);
}

}

How could I use a SortedSet and a Comparator to obtain the desired effect?

Thanks,


Inspired by SJuan76, have finally come up with:

public class FindDupsFinal {
public static void main(String[] args) {
    SortedSet<String> eliminatedDups2 = new TreeSet<String>(IGNORE_CASE);        

    for (String a : args) {
           eliminatedDups2.add(a);
    }
    System.out.println(eliminatedDups2.size() + " distinct words by ignoring case: " + eliminatedDups2);
}

static final Comparator<String> IGNORE_CASE = new Comparator<String>() {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
};

}

Was it helpful?

Solution

SortedSet<String> eliminatedDups =
   new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
Collections.addAll(eliminatedDups, args);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top