Python Counter alternative for Java
2022-09-02 21:56:34
从这里:
Counter 类类似于其他语言中的包或多集。
Java 没有 Multiset 类或类似类。番石榴有一个多集系列,完全可以做你想要的。
在纯Java中,您可以使用Map和新的合并方法:
final Map<String, Integer> counts = new HashMap<>();
counts.merge("Test", 1, Integer::sum);
counts.merge("Test", 1, Integer::sum);
counts.merge("Other", 1, Integer::sum);
counts.merge("Other", 1, Integer::sum);
counts.merge("Other", 1, Integer::sum);
System.out.println(counts.getOrDefault("Test", 0));
System.out.println(counts.getOrDefault("Other", 0));
System.out.println(counts.getOrDefault("Another", 0));
输出:
2
3
0
您可以在几行代码中将此行为包装在类中:
public class Counter<T> {
final Map<T, Integer> counts = new HashMap<>();
public void add(T t) {
counts.merge(t, 1, Integer::sum);
}
public int count(T t) {
return counts.getOrDefault(t, 0);
}
}
并像这样使用它:
final Counter<String> counts = new Counter<>();
counts.add("Test");
counts.add("Test");
counts.add("Other");
counts.add("Other");
counts.add("Other");
System.out.println(counts.count("Test"));
System.out.println(counts.count("Other"));
System.out.println(counts.count("Another"));
输出:
2
3
0
下面是一个类,看起来它实现了足够的功能来执行所需的操作。Counter
static class Counter<T> {
final ConcurrentMap<T, Integer> counts = new ConcurrentHashMap<>();
public void put(T it) {
add(it, 1);
}
public void add(T it, int v) {
counts.merge(it, v, Integer::sum);
}
public List<T> mostCommon(int n) {
return counts.entrySet().stream()
// Sort by value.
.sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))
// Top n.
.limit(n)
// Keys only.
.map(e -> e.getKey())
// As a list.
.collect(Collectors.toList());
}
}
public void test() {
Counter<String> c = new Counter<>();
String[] numbers = {"Zero", "One", "Two", "Three", "Four", "Five", "Six"};
for (int i = 0; i < numbers.length; i++) {
c.add(numbers[i], i);
}
System.out.println(c.mostCommon(3));
}
它使用 Java 8 功能。