gpt4 book ai didi

java - 如何对字符串列表进行降序排序,然后升序排序(如果并列)?

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:08 24 4
gpt4 key购买 nike

好吧,这个问题可能会让你说“什么??”但我会尝试提供一些背景信息。我正在开发一个读取纯文本文件的程序,按单词出现的次数降序对文件中的字符串进行排序,然后对于出现次数相同的单词,我必须按字母升序对这些单词进行排序...

现在我有一个名为“words”的数组列表,其中包含我打开的文本文件中的每个单词。那么,如果出现次数相同,我该如何按出现的单词数量降序排序,然后按字母顺序升序排序呢?

所以如果我有一个列表:

[a, a, a, a, b, c, c, c, c, d, d, e, e, e, e, e]

排序后我的输出列表将是:

e : 5
a : 4 // notice the words that occur 4 times are alphabetical sorted
c : 4
d : 2
b : 1

最佳答案

根据你的问题。

sorts the strings in the file by descending order by number of times that word occurred , then for the words that have the same number of times it occurred, I have to sort those words in ascending alphabetical order...

这意味着

首先,您需要获取一个不同单词列表并计算每个单词的出现次数,这可以使用 HashMap 来实现.

其次,首先按出现次数降序对单词的不同列表进行排序,然后按字母顺序升序,这可以通过实现 Comparator 来实现并使用Collections.sort方法。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SortOccurrence {
Map<String, Integer> wordToOccurenceMap = new HashMap<String, Integer>();

SortOccurrence(List<String> words) {
// Count occurrence for each word
for (String word : words) {
if (!wordToOccurenceMap.containsKey(word)) {
wordToOccurenceMap.put(word, 0);
}
wordToOccurenceMap.put(word, wordToOccurenceMap.get(word) + 1);
}
}

List<String> getSortResult() {
List<String> distinctWords = new ArrayList<String>(wordToOccurenceMap.keySet());
Collections.sort(distinctWords, new OccurrenceComparator());
List<String> sortResult = new ArrayList<String>();
for (String distinctWord : distinctWords) {
sortResult.add(distinctWord + " : " + wordToOccurenceMap.get(distinctWord));
}
return sortResult;
}

public class OccurrenceComparator implements Comparator<String> {

@Override
public int compare(String o1, String o2) {
if (!wordToOccurenceMap.containsKey(o1) || !wordToOccurenceMap.containsKey(o2)) {
throw new IllegalArgumentException("word not occur");
}
// if occurrence same, compare the string
if (wordToOccurenceMap.get(o1).compareTo(wordToOccurenceMap.get(o2)) == 0) {
return o1.compareTo(o2);
}
// compare by occurrence, '-' for descending
return -wordToOccurenceMap.get(o1).compareTo(wordToOccurenceMap.get(o2));
}
}

public static void main(String[] args) {
List<String> input = Arrays.asList(
new String[] { "a", "a", "a", "a", "b", "c", "c", "c", "c", "d", "d", "e", "e", "e", "e", "e" });

SortOccurrence sortOccurence = new SortOccurrence(input);
System.out.println(sortOccurence.getSortResult());
}
}

关于java - 如何对字符串列表进行降序排序,然后升序排序(如果并列)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com