根据重复值排序列表

问题描述 投票:1回答:1

我有一个像这样的字符串列表:{3,2,2,1,1,1,1,4,4,4}并且我想按重复值的数量对它进行排序,使它成为{1, 1,1,1,2,2,4,4,4,3}感谢您的关注

java sorting arraylist duplicates
1个回答
2
投票

您可以使用Collections.frequencyComparator.comparingInt根据重复对列表进行排序

Comparator.comparingInt(i->Collections.frequency(list, i)).reversed()

下面是示例

    List<Integer>  list = new ArrayList<>(List.of(3,2,2,1,1,1,1,4,4,4));

    System.out.println(list);

    list.sort(Comparator.comparingInt(i->Collections.frequency(list, i)).reversed());

    System.out.println(list);  //[1, 1, 1, 1, 4, 4, 4, 2, 2, 3]

不是检查列表中每个元素的频率,而是可以通过将元素分组并计数到Map<Integer, Long>,然后创建另一个排序的列表Collections.nCopies,以其他方式执行此操作>

List<Integer> result = list.stream()
                       .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                       .entrySet()
                       .stream()
                       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                       .map(entry->Collections.nCopies(entry.getValue().intValue(), entry.getKey()))
                       .flatMap(List::stream)
                       .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.