【问题标题】:How to sort an arraylist based on last character in Java? [closed]如何根据Java中的最后一个字符对数组列表进行排序? [关闭]
【发布时间】:2021-03-15 22:19:12
【问题描述】:

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

示例

"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

【问题讨论】:

  • 最后一个字符?您的问题似乎与示例数据相矛盾。

标签: java arrays sorting arraylist


【解决方案1】:

我认为您可以将 lambda 传递给List.<b>sort</b>

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]

注意上述输出与您的预期输出之间的差异是因为t<i><b>h</b></i>e 在字典上位于t<i><b>i</b></i>mes 之前,如果计数相同,则上述代码默认为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2021-05-17
    相关资源
    最近更新 更多