두 개의 List가 있을 때, 중복되는 element 개수를 찾는 방법을 알아보자. 예를들어 list1 = [1, 2, 3, 4, 5], list2 = [4, 5, 6, 7] 가 주어진다면, 중복되는 값은 [4, 5]이므로 2를 찾아내야 한다.

물론 방법은 이거 말고도 무궁무진 하겠지만, 몇가지 예제를 만들어봤다.

  1. 검색 대상인 요소가 하나 뿐이라면, Collections.frequency()를 사용할 수 있다.

     fun main() {
         val list1 = listOf(1, 2, 3, 4, 5)
         val key = 5
         val frequency = Collections.frequency(list1, key)
         println(frequency) // 1
     }
  2. filter 사용하기

    fun main() {
         val list1 = listOf(1, 2, 3, 4, 5, 5)
         val list2 = listOf(3, 4, 5, 6, 7)
         val union = list1 + list2
    
         val intersection = union.groupBy { it }.filter { it.value.size > 1 }.flatMap { it.value }.distinct()
         println(intersection.joinToString()) // 3, 4, 5
    
         val set = union.groupBy { it }.filter { it.value.size == 1 }.flatMap { it.value }
         println(set.joinToString()) // 1, 2, 6, 7
     }
  3. minus 사용하기

    fun main() {
      val list1 = listOf(1, 2, 3, 4, 5)
      val list2 = listOf(3, 4, 5, 6, 7)
    
      val difference = list2.toSet().minus(list1.toSet())
      println(difference.joinToString()) // 6, 7
    
      val duplicationCount = list2.size - difference.size
      println(duplicationCount) // 3
    }
  4. 등장 빈도수까지 똑같은 요소만 찾기

  • groupBy를 사용하면 리스트를 특정한 조건에 따라 Map<K, List> 형식으로 변형할 수 있다.

      fun main() {
          val words1 = "one two three two three".split(' ').groupBy { it }
          val words2 = "one two three four".split(' ').groupBy { it }
          val duplicatedElements = words1.filter { it.value == words2[it.key] }
          println(duplicatedElements)
      }
  • groupingBy, eachCount, eachCountTo를 사용하면 리스트 안에서 특정 조건에 해당되는 원소의 개수를 쉽게 구할 수 있다.

      val frequencies = words.groupingBy { it.first() }.eachCount()
      fun main() {
          val words = "one two three four five six seven eight nine ten".split(' ')
          val frequenciesByFirstChar = words.groupingBy { it.first() }.eachCount()
          println(frequenciesByFirstChar) // {o=1, t=3, f=2, s=2, e=1, n=1}
    
          val moreWords = "eleven twelve".split(' ')
          val moreFrequencies = moreWords.groupingBy { it.first() }.eachCountTo(frequenciesByFirstChar.toMutableMap())
          println(moreFrequencies) // {o=1, t=4, f=2, s=2, e=2, n=1}
          println((frequenciesByFirstChar).filter { it.value == moreFrequencies[it.key] }) // {o=1, f=2, s=2, n=1}
      }