本文介绍了是否存在Python 3的集合的scala / java等价物.Counter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以计算我拥有的对象数量的类 - 收集所有对象然后对它们进行分组听起来更有效。

I want a class that will count the the number of objects I have - that sounds more efficient that gathering all the objects and then grouping them.

Python在,Java或Scala是否有类似的类型?

Python has an ideal structure in collections.Counter, does Java or Scala have a similar type?

推荐答案

来自文档你链接了:

Java没有 Multiset 类或类似物。 有集合,完全符合您的要求。

Java does not have a Multiset class, or an analogue. Guava has a MultiSet collection, that does exactly what you want.

在纯Java中,你可以使用 Map< T,Integer> 和新的 合并 方法:

In pure Java, you can use a Map<T, Integer> and the new merge method:

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

你可以包装这种行为在几行代码的中:

You can wrap this behaviour in a class in a few lines of code:

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

这篇关于是否存在Python 3的集合的scala / java等价物.Counter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!