如何在java中根据最后一个字符对arraylist排序?

y3bcpkx1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(260)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

上个月关门了。
改进这个问题
我有一个数组列表,它显示字符串中每个唯一的单词以及它们出现的次数(每个元素都是一个字符串)
但是我想根据最后一个字符(计数)对数组列表进行排序,有什么方法可以做到这一点吗?
例子:

"it was the best of times it was the worst of times"
was - 2
best - 1
it - 2
the - 2
times - 2
of - 2
worst - 1

预期产量:

it - 2
of - 2
times - 2
the - 2
was - 2
best - 1
worst - 1
raogr8fs

raogr8fs1#

我想你可以把一只羔羊递给我 List.sort :

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Main {
    public static void main(String[] args) {
        String sentence = "it was the best of times it was the worst of times";
        List<String> wordsWithCounts = getWordsWithCountsFromSentence(sentence);

        System.out.println("Before sorting on counts then alphabetically:");
        System.out.println(wordsWithCounts);

        wordsWithCounts.sort((s1, s2) -> {
            String[] s1Split = s1.split(" ");
            String[] s2Split = s2.split(" ");
            String s1Count = s1Split.length != 0 ? s1Split[s1Split.length - 1] : "";
            String s2Count = s2Split.length != 0 ? s2Split[s2Split.length - 1] : "";
            if (!s1Count.equals(s2Count)) {
                return s2Count.compareTo(s1Count); // decreasing order based on counts
            }
            return s1.compareTo(s2); // alphabetically otherwise if same counts
        });

        System.out.println("After sorting on counts then alphabetically:");
        System.out.println(wordsWithCounts);
    }

    private static List<String> getWordsWithCountsFromSentence(String sentence) {
        Map<String, Integer> wordCounts = new LinkedHashMap<>(); // To maintain insertion order for before output
        for (String word : sentence.split(" ")) {
            wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
        }
        return wordCounts.entrySet()
                .stream()
                .map(entry -> String.join(" - ", entry.getKey(), String.valueOf(entry.getValue())))
                .collect(Collectors.toList());
    }
}

输出:

Before sorting on counts then alphabetically:
[it - 2, was - 2, the - 2, best - 1, of - 2, times - 2, worst - 1]
After sorting on counts then alphabetically:
[it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1]

n、 b.上述输出与预期输出之间的差异是因为 the 在前面 times 从词汇上讲,如果计数相同,上面的代码默认为。

相关问题