1. Count
val numbers = listOf(1, -2, 3, -4, 5, -6)
val totalCount = numbers.count()
val evenCount = numbers.count { it % 2 == 0 }
val oddCount = numbers.count { it % 2 != 0 }
fun main() {
// count() : elements의 개수를 return
println("totalCount : $totalCount") // 총 개수
println("evenCount : $evenCount") // 짝수의 개수
println("oddCount : $oddCount") // 홀수의 개수
}
2. associateBy,groupBy,partition
data class Person(val name: String, val city: String, val phone: String) // 1
val people = listOf( // 2
Person("John", "Boston", "+1-888-123456"),
Person("Sarah", "Munich", "+49-777-789123"),
Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))
val phoneBook = people.associateBy { it.phone } // 3
val cityBook = people.associateBy(Person::phone, Person::city) // 4
val peopleCities = people.groupBy(Person::city, Person::name) // 5
val lastPersonCity = people.associateBy(Person::city, Person::name) // 6
val part = people.partition { it.city == "Boston" }
fun main() {
println("phoneBook : $phoneBook")
println("cityBook : $cityBook")
println("peopleCities : $peopleCities")
println("lastPersonCity : $lastPersonCity")
println("part : $part")
}
2-1. associateBy : 지정된 key로 Map을 반환
2-2. groupBy : 지정된 key로 Map을 반환
2-3. partition : 조건에 의해 배열로 나누어 반환
2-3. partition
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val evenOdd = numbers.partition { it % 2 == 0 } // 2
val (positives, negatives) = numbers.partition { it > 0 } // 3
println("Numbers: $numbers")
println("Even numbers: ${evenOdd.first}")
println("Odd numbers: ${evenOdd.second}")
println("Positive numbers: $positives")
println("Negative numbers: $negatives")
}
'Kotlin' 카테고리의 다른 글
코틀린 zip, getOrElse (0) | 2022.02.28 |
---|---|
코틀린 map,flatmap,<minOrNull,maxOrNull>, sorted (0) | 2022.02.28 |
코틀린 <find,findlast>, <first,last>,<firstOrNull,lastOrNull> (0) | 2022.02.28 |
코틀린 Filters, Maps,<any,all,none> (0) | 2022.02.28 |
코틀린의 Collcetions (0) | 2022.02.24 |