簡體   English   中英

我們可以按Map中的鍵和值對Set進行排序嗎?

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

我有一個Car類,代表汽車的名稱和ID:

public class Car {
String name;
int ID;
}

另一個代表種族的類,在該類中,我需要按種族在比賽中對汽車進行排序:

public class Race {
private Set<Car> cars = new TreeSet<>();
private Map<Integer, Integer> races = new TreeMap<>();//key represents the order in race, value represents the ID of a car, so i need to sort cars by the keys in races
...
public Collection getSortedCars() { ??? }
}

-任何想法如何獲得分類的汽車? 非常感謝

編輯:對不起,我使用了非常不好的示例與值,所以這與標識符,我希望你得到我所需要的。

不會用SortedSet的做到這一點,甚至雖然可以使用自定義的比較 原因是因為可以修改種族,從而使 TreeSet內部的任何結構無效 ,從而使行為“不可預測”。

相反,我將使getSortedCars首先從Set中獲取一個序列(例如List),然后排序並返回這樣的序列。

實際的排序對於Collections.sort和自定義的Comparator是“瑣碎的”,因為這實際上是“ sort by”操作,例如:

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM