【问题标题】:Sort arraylist by number of times in arraylist and then remove duplicates按arraylist中的次数对arraylist进行排序,然后删除重复项
【发布时间】:2012-08-22 09:14:08
【问题描述】:

现在我在 php 中有一些看起来像这样的东西:

$count = array_count_values($result);
arsort($count);

foreach($count as $key => $val){
    $result[] = $key;
}

它将计算数组中的所有项目并将其放入键/值对中。这将删除重复项,然后我告诉它进行排序。然后我拿它的钥匙并存储它。有没有办法在 Java 中做到这一点?

【问题讨论】:

  • 我不认为你的代码正在做你认为它正在做的事情。 arsort 不按数组中的值排序。它按键排序。

标签: java list sorting arraylist duplicates


【解决方案1】:

我认为 Java 没有与 array_count_values 函数等效的功能,因此您需要自己实现它。像这样的:

public static <T> Map<T, Integer> countValues(List<T> values) {
    Map<T, Integer> result = new HashMap<T, Integer>();
    // iterate through values, and increment its corresponding value in result
    return result;
}

然后使用java.util.Collections.sort(List list, Comparator c) 函数按计数对数组进行排序。您需要实现 Comparator 以按计数排序。

public class CountComparator<T> implements Comparator<T> {
    private Map<T, Integer> counts;

    public CountComparator(Map<T, Integer> counts) {
        this.counts = counts;
    }

    public int compare(T o1, T o2) {
        // assumes that the map contains all keys
        return counts.get(o1).compareTo(counts.get(o2));
    }
}

【讨论】:

    【解决方案2】:

    如何使用来自 Google Guava 库的 Multiset 来获取计数。它的工作方式与 PHP 的 array_count_values 类似。

    如果您希望它按键排序,则使用TreeMultiset 实现。

    如果您想按计数排序,请使用Multisets.copyHighestCountFirst

    【讨论】:

    • 如果您希望它按计数排序,那么该博文是out of date
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 2021-09-16
    • 2019-11-15
    相关资源
    最近更新 更多