Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a scala replacement for Guava MultiSet and Table concepts?

To use guava Table and Multiset in scala? are there already different concenpts in scala instead of importing guava library for this usage?

like image 234
Jas Avatar asked Oct 15 '25 16:10

Jas


1 Answers

You could use Map[(R, C), V] instead of Table<R, C, V> and Map[T, Int] instead of Multiset<T>. You could also add helper methods to Map[T, Int] like this:

implicit class Multiset[T](val m: Map[T, Int]) extends AnyVal {
  def setAdd(e: T, i: Int = 1) = {
    val cnt = m.getOrElse(e, 0) + i
    if (cnt <= 0) m - e
    else m.updated(e, cnt)
  }
  def setRemove(e: T, i: Int = 1) = setAdd(e, -i)
  def count(e: T) = m.getOrElse(e, 0)
}

val m = Map('a -> 5)

m setAdd 'a
// Map('a -> 6)

m setAdd 'b
// Map('a -> 5, 'b -> 1)

m setAdd ('b, 10)
// Map('a -> 5, 'b -> 10)

m setRemove 'a
// Map('a -> 4)

m setRemove ('a, 6)
// Map()

m count 'b
// 0

(m setAdd 'a) count 'a
// 6
like image 124
senia Avatar answered Oct 17 '25 12:10

senia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!