是否存在Python 3的集合的scala / java等价物.Counter [英] Is there a scala/java equivalent of Python 3's collections.Counter

查看:139
本文介绍了是否存在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在 collections.Counter ,Java或Scala是否有类似的类型?

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

推荐答案

来自文档你链接了:


Counter类与其他语言的包或多重集相似。

The Counter class is similar to bags or multisets in other languages.

Java没有 Multiset 类或类似物。 Guava 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆