title: Intersection of two lists maintaining duplicate values in Kotlin
body: <p>I want to find the number of common elements between two lists without eliminating duplicates.  </p>
  
  <p>For example:</p>
  
  <hr>
  
  <p>input: <code>[1, 3, 3]</code> &amp; <code>[4, 3, 3]</code></p>
  
  <p>output: <code>2</code>, since the common elements are <code>[3, 3]</code></p>
  
  <hr>
  
  <p>input: <code>[1, 2, 3]</code> &amp; <code>[4, 3, 3]</code></p>
  
  <p>output: <code>1</code>, since the common elements are <code>[3]</code></p>
  
  <hr>
  
  <p>If I were to use the Kotlin collections <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/intersect.html" rel="nofollow noreferrer">intersect</a>, the result is a set, which will prevent me from counting duplicate values. </p>
  
  <p>I found (for Python) <a href="https://stackoverflow.com/questions/26663371/python-intersection-of-two-lists-keeping-duplicates">this</a>, which handles duplicates differently and <a href="https://stackoverflow.com/questions/37645053/intersection-of-two-lists-including-duplicates">this</a>, which led me to use <a href="https://stackoverflow.com/a/37645155/4455466">this</a> implementation, where <code>a</code> and <code>b</code> are the lists: </p>
  
  <pre><code>val aCounts = a.groupingBy { it }.eachCount()
  val bCounts = b.groupingBy { it }.eachCount()
  var intersectionCount = 0;
  for ((k, v) in aCounts) {
      intersectionCount += Math.min(v, bCounts.getOrDefault(k, 0))
  }
  </code></pre>
  
  <p>However, being new to Kotlin I'm wondering if there's a more "Kotlin-y" way to do this--something taking advantage of all Kotlin's collections functionality?  Maybe something that avoids explicitly iterating?</p>