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 has an ideal structure in collections.Counter, does Java or Scala have a similar type?
From the documentation that you linked:
The Counter class is similar to bags or multisets in other languages.
Java does not have a Multiset
class, or an analogue. Guava has a MultiSet
collection, that does exactly what you want.
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));
Output:
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);
}
}
Use like this:
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"));
Output:
2
3
0
Not as far as I know. But scala is very expressive, allowing you to cook something like it yourself:
def counts[T](s: Seq[T]) = s.groupBy(x => x).mapValues(_.length)
Edit: Even more concise with:
def counts[T](s: Seq[T]) = s.groupBy(identity).mapValues(_.length)
Another scala version, doing it in one pass and avoiding .groupBy
val l = List("a", "b", "b", "c", "b", "c", "b", "d")
l.foldLeft(Map[String, Int]() withDefaultValue (0))
{ (m, el) => m updated (el, m(el)+1)}
//> res1: Map(a -> 1, b -> 4, c -> 2, d -> 1)
or if you don't want a map with default value zero
l.foldLeft(Map[String, Int]()) { (m, el) => m updated (el, m.getOrElse(el,0)+1)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With