首页 > 解决方案 > 如何根据Java中的最后一个字符对数组列表进行排序?

问题描述

我有一个数组列表,它显示字符串的每个唯一单词以及它们出现的次数(每个元素都是一个字符串)
但是我想根据最后一个字符(即计数)对数组列表进行排序,有没有方法去做这个?

示例

"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

标签: javaarrayssortingarraylist

解决方案


我认为您可以将 lambda 传递给: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]

注意上述输出与您的预期输出之间的差异是因为在字典顺序之前出现,如果计数相同,上述代码默认为。thetimes


推荐阅读