java - 如何使用 Java Comparator 使用两个参数对 ArrayList 进行排序?

标签 java arraylist comparator

我使用 Java Comparator 按词频属性的降序对 Word 对象的 ArrayList 进行排序。创建 Word 对象时,首先使用 HashMap 从 .txt 文件中读取单词,然后将 HashMap 转换为 Word 对象的 ArrayList。然后我想按字母顺序对频率相同的单词进行排序。

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

关于java - 如何使用 Java Comparator 使用两个参数对 ArrayList 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53487307/

相关文章:

Kotlin:从类的属性生成 Comparable#compareTo() 函数

java - 新 Mavenized 项目 - 找不到类路径

java - 安卓应用扩展包

java - 如何正确创建 ArrayList?

Java - 如何检查两个 ArrayList 是否是唯一对象(即使它们具有相同的值)?

java - Comparable 不排序对象

java - Hadoop MapReduce : Is it possible to write mapper output to separate output files(not intermediate ones) without setting number of reducers to zero?

Java如何在运行时链接库

java - 访问List<List<List<List<Object>>>> titles = new ArrayList<List<List<Object>>>>();

java - Comparator.nullsLast 不会避免 NullPointerException