CodeGym /행동 /Kotlin SELF /groupingBy().eachCount() — group list eopshi bindo su(req...

groupingBy().eachCount() — group list eopshi bindo su(requency) segi

Kotlin SELF
레벨 24, 레슨 1
사용 가능

1. Bindo: uri-ga jeongmal eotgo sip-eun geon mueosinga

Cheoeum “bindo”reul deureumyeon jom jichanh-eun tonggyereul tteoollil su itjiman, silje-ro-neun data-reul 다룰 ttae gajang yuyonghan mini yeonsan jung hanaga bindo imnida. Bindo-neun “myeot beon natanassneun-ga…”e daehan dab imnida. Kategori byeol jichul geonsu, sayongjaga eotteon commandreul myeot beon ipryeokhaessneunji, tekseuteu-e eotteon jongryuui dan-eoga myeot ga inneunji — i modeun geosi bindo imnida.

Kotlin type 관점eseo uri-ga boyeonhi wonhaneun gujo-neun da-eum-gwa gateumnida:

  • key — “mueoseul seginunji”(kategori, dan-eo, cheot geulja, suja deung)
  • value — “myeot beon natanassneunji”

Jeuk, gyeolgwa-neun bindo map imnida:

Map<K, Int>

“saram iyagi cheoreom” ye:

  • "food" -> 12 (food kategori-e 12gae record)
  • "taxi" -> 3
  • "kotlin" -> 2

I ttae daeum-gwa gateun saenggag-i jaju deul-eo-opsnida: “MutableMapeul mandeulgo countreul son-euro 1ssik ollyeoya haetjanh-a?” Ige pyeonhan bangbeob-il su itjiman, Kotlin standard library-neun i geoseul han jul-euro kkeunnael su itge haejumyeo, geu ttae deungjanghaneun geosi baro groupingBy { ... }.eachCount() seuthap imnida.

2. Wae groupByga hangsang count-e jeokhabhaji anheun-ga

이미 groupByreul algo issdamyeon aju jayeonseureoun saenggag-i deumnida: “OK, group-eul mandeulgo, 각 group-ui sizereul bomyeon doegetne.” Jinjja doena? Doemnida. Pyeonhana? Ttaeron geureohjiman. Haji-man nuance-ga innseubnida: groupByneun Map<K, List<T>>reul banhwanhago, geu mal-eun gak key byeol ro element list jeonche reul bogwanhandaneun geos imnida.

Hajiman uri-ga piryohan geon “myeot”dan-eul ppun-irimyeon, list bogwan-eun bulpilyohaejimnida:

  • list-neun memoryreul jomukhamnida;
  • list-reul saengseonghago 채워야 합니다;
  • gyeolguk listreul suja(size)ro bakkun dae-e, detail-eun beorige doemnida.

Ige-neun jom ireoke bigyohal su issseubnida: “party-e eolmana manheun sarami wasseul까?”reul algo sipeunde, irum byeol ro bang-eul hana-ssik mandeulgo, saramdeul-eul gageum bang-euro deureogage han dae-e, geu bang-e issneun saram sureul sen dwi… baro nollaeso modeun saram-eul nae보내neun geot-gat-eoyo. Hyeoryuljeog-ihagin hajiman jom geukjeog-imnida.

“Geunyang se-gi”reul wihayeo Kotlin-eun dareun gil-eul jepgyehamnida: meonjeo “gak elementeseo keyreul eotteoke gyesanha-neunji algo issda”reul malhago, geu dae-e “key byeol element sureul seg-eo jwo”reul yocheonghamnida. Geu geosi baro groupingBy { ... }.eachCount()ga haneun il imnida.

3. groupingBy { ... }ran mueos-igo, wae ajik Map-i anin-ga

groupBy dwi-e-neun “grouping-eun hang-sang Mapeul dollyeojunda”raneun 기대-ga saenggigil su issseubnida. Hajiman groupingByneun dareuge dongjakhamnida. Ige-neun map-i anira, Groupinggwa gateun teukbyeolhan objectreul banhwanhamnida. I objecte-neun “key gyesan 로직”i deureo issgo, silje gyeolgwa-neun 나중에 aggregation yeonsan-eul jeogyonghal ttae saenggimnida.

Type-man bomyeon choejeonhaeng ihaega eoryeoul su isseunikka, saenggag-eul du dan-gye-ro nareobolsu issseubnida:

  1. “elementeseo keyreul eotteoke eodneunji gyuchik-eul jeongha”
  2. “geu gyuchik-e aggregation yeonsan-eul jeogyongha: ye를 들어 count해”

Code-neun ireohge boimnida:

fun main() {
    val words = listOf("one", "two", "one")

    val grouping = words.groupingBy { it } // ajik Map-i 아니다!
    val freq = grouping.eachCount()        // ije ya Map<String, Int>

    println(freq) // {one=2, two=1}
}

Yeogi-eseo jungyohan point: groupingBy { ... }neun “cheongu(requisition)reul jeochangha-neun” geot-gatgo, eachCount()neun “wanseongdoen bogoseoreul 받는” geot-gatseubnida.

4. eachCount(): bindo map Map<K, Int> eodneun beop

eachCount()reul 호출하면, Kotlin-eun uri-ga wonhaneun geot-eul geunyang haejum니다: 각 key byeol ro element sureul dam-eun map-eul dollyeojumnida.

Gajang gibon ye: dan-eo bindo

fun main() {
    val words = listOf("one", "two", "one", "three", "two")

    val freq: Map<String, Int> = words
        .groupingBy { it }
        .eachCount()

    println(freq) // {one=2, two=2, three=1}
}

Joheun jeom-eul bwaseyo: MutableMapdo piryohaji 않고, putdo piryohaji 않고, “keyga isseumyeon +1, eopseumyeon 1” gateun boilerplate-do piryohaji 않습니다. Kotlin-i jeonbu dae신 cheorihamnida.

Gyeseon-doen key ye: cheot geulja-ro grouping

I yeje-neun key(Char)ga 원본 element(String)gwa dareul su issdaneun geoseul jal boyeojumnida.

fun main() {
    val words = listOf("one", "two", "three", "four", "five")

    val freqByFirstChar = words.groupingBy { it.first() }.eachCount()

    for ((ch, count) in freqByFirstChar) {
        println("$ch -> $count")
        // o -> 1
        // t -> 2
        // f -> 2
    }
}

Yeogi-eseo han beon-e se gaji skill-eul hamkke yeonseubhamnida: groupingBy 안의 lambda, Char 처리, 그리고 Map 순회를 (key, value) deconstruction-euro haneun beop imnida.

5. Count jeon key normalisation

Silje data-eseo-neun bindo se-gi jasinboda “gateun geot”i 다르게 bo이는 geot-i 더 큰 munje-in gyeongu-ga manhseubnida. gongbaek, 대소문자, amugeona kkeuneun bujeonghyeok moonja deung-i “geot cheoreom boineun dareun key”reul mandeulmida.

Yeogi-eseo gieokhaeya hal dan-sunhan gyuchik: key normalisation-eul groupingBy { ... } naebu-eseo jikjeop hasipsio. geu jariga “mueos-eul gateun geot-euro bolji”reul jeonghaneun got-igil ttaemunimnida.

fun main() {
    val drinks = listOf("Tea", " tea ", "TEA", "Coffee")

    val freq = drinks
        .groupingBy { it.trim().lowercase() }
        .eachCount()

    println(freq) // {tea=3, coffee=1}
}

Ige-neun Kotlin-i olbareun design-euro “mil-eo jul” ttae-inde, “grouping key”neun 독립적인 개념이라는 점입니다. “입력 그대로”가 아니라, “내부 데이터 세계에서의 표준 형태”가 되어야 합니다.

Mann약 프로젝트-eseo kategori-ga nune tteuge “heulleojinda”(예: sayongjaga " Taxi "reul ipryeok)면, normalisation-eun tonggye pumsil-eul ol리는 jeongdo-ga 아니라 bogoseo-ui uimi jeonche-reul sal리는 일일 su issseubnida.

6. Practice: kategori byeol jichul geonsu 세기

Ije course-eseo console projectga han beon deungjanghaessseubnida(collections part-eseo sijak). gan-danha게 jichul-eul gwanriha-neun 가상 project imnida. Ajik OOP jeon-ida 보니, record-neun gajang dan순하게: Triple(category, amount, note) 형태로 bogwanhaegessseubnida.

Jageun data set-eul mandeulgo, “gak kategori-e recordga myeot ga inneunji”reul 세는 함수를 작성해 봅시다. Oneul-eun record geonsureul 세는 것이고, geum-aeg hap계(sum)reul 구하는 것이 아닙니다. 합계도 중요하지만, 그건 다른 연산입니다.

Data wa kategori byeol count

fun main() {
    val expenses: List<Triple<String, Int, String>> = listOf(
        Triple("food", 120, "groceries"),
        Triple("Food ", 80, "snack"),
        Triple("taxi", 250, "airport"),
        Triple("TAXI", 90, "home")
    )

    val countsByCategory = expenses
        .groupingBy { (category, _, _) -> category.trim().lowercase() }
        .eachCount()

    println(countsByCategory) // {food=2, taxi=2}
}

Yeogi-eseo 잠깐 멈춰서 lambda-reul nun-euro ilgeoboseyo: (category, _, _) -> .... Ige-neun Triple deconstruction-imnida. Ije Pair/Triple part-eseo baeun neoyong-gwa gatseubnida. uri-ga myung확하게 말하는 geos: “key-neun normalised category다.”

Function-euro bun리(main-i keojigi jeon-e)

fun countExpensesByCategory(expenses: List<Triple<String, Int, String>>): Map<String, Int> {
    return expenses
        .groupingBy { (category, _, _) -> category.trim().lowercase() }
        .eachCount()
}

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("Food ", 80, "snack"),
        Triple("taxi", 250, "airport")
    )

    val counts = countExpensesByCategory(expenses)
    println(counts) // {food=2, taxi=1}
}

Silmu 관점-eseo i dan-gye-neun aju jungyohamnida: countExpensesByCategory(...)ga report-reul wihan jageun building block-i doemnida. Geu functioneun printreul 하지 않고 sun수한 결과(map)reul dol려줍니다. Geureomyeon 나중에 출력 formatting-eul eotteon 방식으로든 예쁘게 바꿀 수 있습니다.

7. Key-neun mueos-ido doel su itda: string, number, boolean

Ttaeron bindo-ga “dan-eo”e만 해당된다고 느껴질 su 있지만, silje-ro key-neun eotteon type-ido 될 수 있습니다: Int, Char, Boolean, 심지어 더 복잡한 것들도요(하지만 지금은 복잡하게 하지 맙시다).

Suja bindo

fun main() {
    val numbers = listOf(10, 10, 20, 30, 30, 30)

    val freq = numbers.groupingBy { it }.eachCount()

    for ((n, count) in freq) {
        println("$n -> $count")
        // 10 -> 2
        // 20 -> 1
        // 30 -> 3
    }
}

“jjak / hol” bindo

Key-neun Booleanimnida: jjak수면 true, hol수면 false. cheoeum-eun isanghage deullil su 있지만, han beon bo면 eolmana pyeonhanji al게 됩니다.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)

    val freq = numbers
        .groupingBy { it % 2 == 0 }
        .eachCount()

    println(freq) // {false=3, true=3}
}

Naeil i gyeolgwareul “jjak su-ga myeot ga”cheoreom saram-i ikgi pyeonhage pyohyeonhago sipdamyeon, geugeon count munje-ga 아니라 formatting munje입니다. Jeuk, responsibility separationgwanjeom-eseo ol바른 흐름입니다.

Sonsuro se-gi vs eachCount()

Ttaeron “suso ro hajamyeon eotteoke doeneunji”reul han beon bwajiboge doemyeon standard libraryga mueoseul haejuneunji deo jal gamsaha게 됩니다. “kategori bindo se-gi” munje-reul batass다고 saenggak하고 MutableMapeuro jjakseonhaebomyeon ireoh습니다.

fun main() {
    val categories = listOf("food", "food", "taxi")

    val counts = mutableMapOf<String, Int>()
    for (c in categories) {
        val old = counts[c] ?: 0
        counts[c] = old + 1
    }

    println(counts) // {food=2, taxi=1}
}

I code-neun jeong상이고, algorithm의 본질을 이해하는 데도 도움이 됩니다. Hajiman silmu-eseo-neun 더 짧고 더 명확한 형태를 원하죠:

fun main() {
    val categories = listOf("food", "food", "taxi")

    val counts = categories.groupingBy { it }.eachCount()
    println(counts) // {food=2, taxi=1}
}

Jungyohan saenggak: eachCount()ga “우주에서 떨어진 마법”이 아닙니다. Geugeon “key byeol counter” pattern-eul standard-ro 잘 구현한 것일 뿐이며, code-reul 덜 시끄럽게(less noisy) 만듭니다.

8. groupingBy().eachCount() sayong si jaju naneun silsu

Error 1: groupingBy { ... }ga baro Mapeul banhwanhal georago gidahaegi.
groupByreul jal sseossdamyeon, son-i jayeonseureopge val m = list.groupingBy { ... }reul sseugo, 곧바로 m["key"]reul hago 싶어집니다. Hajiman groupingByneun 중간 객체(의미상 “grouping plan”)reul 돌려주고, map-eun eachCount() 같은 연산을 적용한 뒤에야 얻습니다. “wae Mapcheoreom jeop근이 안 되지?”raneun munje-ga tteo오르면, du beonjjae dan-gye-reul 빼먹은 것입니다.

Error 2: “deoreoun key”ro bindo-reul sego isanghan gyeolgwareul bogi.
Kategori "Taxi", " taxi ", "TAXI"ga dareun key로 취급되면, munje-neun eachCount()e issneun geosi 아닙니다. eachCount는 “당신이 세라고 한 것”을 그대로 셉니다. Haegyeol: groupingBy 안에서 key를 normalise 하세요. 대개 trim().lowercase()면 충분합니다. Report-eseo-neun 특히 치명적입니다: 잘못된 key = 잘못된 통계입니다.

Error 3: “record geonsu”wa “value sum”reul hon동하기.
eachCount()neun group-e 들어간 element sureul 셉니다. 만약 지출이 ("food", 100)과 ("food", 200)이라면, "food" key의 결과는 2이지 300이 아닙니다. Ige bugdo 아니고 함정도 아닙니다 — 단지 다른 문제입니다. 오늘은 “얼마나 많나(몇 개나)”를 풀고 있고, “얼마의 합인가”를 푸는 게 아닙니다.

Error 4: map-eul printhaego “예쁜 순서”reul 기대하기.
println(freq)reul 하면 Kotlin-eun map-eul “되는 대로” 출력합니다(순서는 내부 구현에 의존). Debugging-eseo-neun 괜찮지만, report-e서는 거의 항상 다음 단계가 필요합니다: 정렬, formatting, 정렬 맞추기. “정확한데 보기 안 좋다”는 느낌이 들면, 그건 count 문제가 아니라 결과 표현 문제이며, 지극히 정상입니다.

Error 5: lambda 안에서 key 계산을 너무 복잡하게 만들어 가독성을 잃기.
Ttaeron groupingBy 안에 반 화면짜리 로직을 넣고 싶어질 수 있습니다. Technically는 가능하지만 금방 읽기 어려워집니다. Key 계산이 복잡하다면, key 계산을 별도 함수(예: normalizeCategory(category: String): String)로 빼고, groupingBy에는 한 줄의 명확한 표현만 남기세요.

1
과제
Kotlin SELF, 레벨 24, 레슨 1
잠금
음료 주문
음료 주문
1
과제
Kotlin SELF, 레벨 24, 레슨 1
잠금
시작 문자
시작 문자
1
과제
Kotlin SELF, 레벨 24, 레슨 1
잠금
스탠드의 해시태그
스탠드의 해시태그
1
과제
Kotlin SELF, 레벨 24, 레슨 1
잠금
명령 로그
명령 로그
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION