簡體   English   中英

如何使用Java Comparator使用兩個參數對ArrayList進行排序?

[英]How to use Java Comparator to sort an ArrayList using two parameters?

我已經使用Java比較器按Word頻率屬性的降序對Word對象的ArrayList進行排序。 通過首先使用哈希圖從.txt文件中讀取單詞,然后將哈希圖轉換為Word對象的ArrayList來創建Word對象。 然后,我想按字母順序對具有相同頻率的單詞進行排序。

   while (reader.hasNext()) {
            word = reader.next().toLowerCase();
            word = word.substring(0, 1).toUpperCase() + word.substring(1);
            word = word.replaceAll("[^a-zA-Z ]", "");
            if (!word.contains("0") || !word.contains("1") || !word.contains("2") || !word.contains("3") || !word.contains("4") || !word.contains("5") || !word.contains("6") || !word.contains("7") || !word.contains("8") || !word.contains("9") || !word.contains("-") || !word.contains("_")) {
                // This is equivalent to searching every word in the list via hashing (O(1))
                if(!frequencyMap.containsKey(word)) {
                     frequencyMap.put(word, 1);
                } else {
                        // We have already seen the word, increase frequency.
                        frequencyMap.put(word, frequencyMap.get(word) + 1);
                }
            }
            counter++;
        }

 for(Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {
    Word word = new Word(entry.getKey());
    word.frequency = entry.getValue();
    wordList.add(word);
 }
 Collections.sort(wordList, Word.WordFrequency);

public class Word {

    String value;
    int frequency;

    public Word(String v) {
        value = v;
        frequency = 1;
    }

    public String getValue() {
        return value;
    }

    public int getFrequency() {
        return frequency;
    }

    public static Comparator<Word> WordFrequency = new Comparator<Word>() {
        public int compare(Word w1, Word w2) {
            int w1Frequency = w1.getFrequency();
            int w2Frequency = w2.getFrequency();
            return w2Frequency-w1Frequency;
        }
    };
}

請參見thenComparing方法,該方法可讓您在有關系時提供比較鍵:

// sort using 'd' will sort 1st alphabetically, then by length
// (this is a totally arbitrary example)
Comparator<String> c = String::compareTo;
Comparator<String> d = c.thenComparing(s -> s.length());

暫無
暫無

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

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