java - 按 arraylist 中的次数对 arraylist 进行排序,然后删除重复项

标签 java list sorting arraylist duplicates

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

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

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

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

最佳答案

我认为 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)函数按计数对数组进行排序。您需要实现比较器来按计数排序。

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));
    }
}

关于java - 按 arraylist 中的次数对 arraylist 进行排序,然后删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149498/

相关文章:

java - 当输入偶数时尝试重复该方法时出现堆栈溢出

python - 在 Python 中展平通用 JSON 字典列表或列表

arrays - 如何从 flutter 中的另一个列表中获取最高值列表

javascript - JS : Sort List Items based on data-element

c++ - 通过向右移动对值数组进行排序

java - 如何根据组合选择删除JTable中的行

java - SQLiteConstraintException : How to map "no relationship" with a FOREIGN KEY in Room

java - List<String> 作为 GET 方法的输入

java - 使用合并排序与选择排序的比较

java - 如何模拟InputStream和ByteString