现在我在 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/