簡體   English   中英

根據從地圖獲得的優先級對ArrayList進行排序(Java版本<Java8)

[英]Sort an ArrayList based on Priorities obtained from a Map (Java version < Java8)

最好的方法是根據從映射獲得的優先級對具有字符串的ArrayList進行排序。

例如:我有一個Map,其中為特定用例分配了優先級(鍵:我在字符串和值中尋找的模式,值:該模式的優先級)

Map pMap= new HashMap();
pMap.put("", 1);
pMap.put("1", 2);
pMap.put("2", 3);
pMap.put("3", 4);
pMap.put("4", 5);
pMap.put("*", 6);

List<String> listToBeSorted= new ArrayList<>();
listToBeSorted.add("Axxxx");
listToBeSorted.add("Ax4xx");
listToBeSorted.add("px*xxx");
listToBeSorted.add("px1xx");

我想根據第三個字符為列表中的每個字符串分配優先級,並根據獲得的優先級對列表進行排序。

我的方法:

以listToBeSorted為對象,對其進行迭代並獲取每個字符串的優先級,然后將其插入到Temp Hashmap中,其中鍵為String,值為Priority。 最后,返回帶有排序鍵的新Arraylist。

預期結果:包含以下數據的Arraylist:

Axxxx
px1xx
Ax4xx
px*xxx

這種方法目前有效,但是當數據量很大時,我認為這不是一個好的方法。

有解決這個問題的更好方法嗎?

PS:我知道Java 8中有一個更好的解決方案,但是不幸的是我無法使用它。因此,如果有人可以給我一個更好的解決方案而不是Java8,那就太好了嗎?

預先感謝您的寶貴時間。

您只需要一個比較器即可根據兩個字符串的優先級對其進行比較:

Comparator<String> priorityBasedComparator = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        int priority1 = pMap.get(s1.substring(2, 3));
        int priority2 = pMap.get(s2.substring(2, 3));
        return Integer.compare(priority1, priority2);
    }
}
Collections.sort(list, priorityBasedComparator);

當然, pMap應該聲明為Map<String, Integer>而不是原始Map(您永遠不要使用原始類型)。 並且final應該可以從比較器中使用。

暫無
暫無

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

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