Can we sort a Set by keys and values in Map?

后端 未结 1 1466
自闭症患者
自闭症患者 2021-01-25 20:44

i have a class Car representing name and IDs of cars:

public class Car {
String name;
int ID;
}

and another class representing races in which i

相关标签:
1条回答
  • 2021-01-25 21:30

    I would not do this with a SortedSet, even though a custom Comparator could be used. The reason is because the races could be modified and thus invalidate any structure inside the TreeSet making the behavior "unpredictable".

    Instead, I would make getSortedCars first get a sequence (e.g. a List) from the Set, and then sort and return such a sequence.

    The actual sorting is "trivial" with Collections.sort and a custom Comparator as this is really a "sort by" operation, for instance:

    class CompareCarsByWins implements Comparator<Car> {
        Map<Car,Integer> wins;
    
        public CompareCarsByWins(Map<Car,Integer> wins) {
            this.wins = wins;
        }
    
        public int compareTo (Car a, Car b) {
            // Actual code should handle "not found" cars as appropriate
            int winsA = wins.get(a);
            int winsB = wins.get(b);
            if (winsA == winsB) {
                // Tie, uhm, let's .. choose by name
                return a.getName().compareTo(b.getName());
            } else {
                // Sort most wins first
                return winsB - winsA;
            }
        }
        // ..
    }
    
    // Usage:
    List<Car> results = new ArrayList<Car>(cars);
    Collections.sort(results, new CompareCarsByWins(races));
    
    0 讨论(0)
提交回复
热议问题