Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

sorting - How to sort and avoid duplicates in TreeSet in java with my comparator

I wan to create TreeSet() that will sort my elements with my predefined comparator. But the problem is when I give the comparator as a parametar to the constructor of the TreeSet(MyComparator), the TreeSet is not avoiding duplicates. Can i achieve sorting of the elements and avoiding duplicates?

The comparator looks like:

public static Comparator<Participant> byNameAndAge = (L,R) ->{
        //check if they have the same code
        if(L.code.equalsIgnoreCase(R.code))
            return 0;

        int res = L.name.compareToIgnoreCase(R.name);
        if(res ==0)
            res = Integer.compare(L.age,R.age);
        return res;
    };
question from:https://stackoverflow.com/questions/65829164/how-to-sort-and-avoid-duplicates-in-treeset-in-java-with-my-comparator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've misunderstood a few things. TreeSet does eliminate duplicates, with 'a duplicate' defined as 'any two elements for which your compare method returns 0'. No 2 such elements can both exist in a treeset. I'm sure your code doesn't work if you say so, but the code you pasted isn't the problem, nor is TreeSet's code.

A trivial example:

Comparator<String> byLength = (a, b) -> a.length() - b.length();
Set<String> set = new TreeSet<String>(byLength);
set.add("Hello");
set.add("World");
set.add("X");
set.add("VeryLong");
System.out.println(set);

> [X, Hello, VeryLong]

Note how 'World' disappeared, because the comparator says it is equal to Hello (they are both 5 length, a.length() - b.length() is returning 0, and 0 is 'equal, thus, eliminate the duplicate' according to treeset). In other words, your code as pasted would eliminate duplicates, the problem lies elsewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...