// 예제 데이터
data class Fruit(
val id: Long,
val name: String,
val factoryPrice: Long,
val currentPrice: Long
)
// 사과만 필터링
val apples = fruits.filter { it.name == "사과" }
// 필터에서 인덱스가 필요한 경우
val apples = fruits.filterIndexed { idx, fruit ->
println(idx)
fruit.name == "사과"
}
// 사과 가격을 알고 싶다
val applePrices = fruits
.filter { it.name == "사과" }
.map { it.currentPrice }
// 맵에서 인덱스가 필요한 경우
val applePrices = fruits
.filter { it.name == "사과" }
.mapIndexed { idx, fruit ->
println(idx)
fruit.currentPrice
}
// 매핑 결과가 null이 아닌 것만 가져오고 싶은 경우
val values = fruits.filter { it.name == "사과" }
.mapNotNull { it.nullOrValue() }
all
: 조건을 모두 만족하면 true
, 아니면 false
// 과일이 모두 사과인가?
val isAllApple = fruits.all { it.name == "사과" }
none
: 조건을 모두 불만족하면 true
, 아니면 false
// 사과가 하나도 없는가
val isNotApple = fruits.none { it.name == "사과" }
any
: 조건을 하나라도 만족하면 true
, 아니면 false
// 10000원 이상인게 하나라도 있는가
val isNoApple = fruits.any { it.factoryPrice >= 10000 }
sortedBy
: 정렬// 현재가로 오름차순 정렬
val sortedFruits = fruits.sortedBy { it.currentPrice }
// 현재가로 내림차순 정렬
val sortedFruits = fruits.sortedByDescending { it.currentPrice }
distinctBy
: 변형된 값 기준으로 중복을 제거// 이름 기준 중복 제거 후 이름만 추출
val distinctFruitNames = fruits.distinctBy { it.name }
.map { it.name }
firt
: 첫번째 값을 가져오고 무조건 null
이 아니어야 한다. (아니면 예외)
fruits.first()
firtstOrNull
: 첫번째 값 또는 null
반환
fruits.firstOrNull()
last
fruits.last()
lastOrNull
fruits.lastOrNull()
// 이름 -> List<과일>
val map: Map<String, List<Fruit>> = fruits.groupBy { it.name }
// id -> 과일
val map: Map<Long, Fruit> = fruits.associateBy { it.id }
// 이름 -> List<출고가>
val map: Map<String, List<Long>> = fruits
.groupBy({ it.name }, { it.factoryPrice })
// id -> 출고가
val map: Map<Long, Long> = fruits
.associateBy({ it.id }, { it.factoryPrice })
Map
에 대해서도 filter
등의 기능을 사용할 수 있다.val map = fruits.groupBy { it.name }
.filter { (key, value) -> key == "사과" }
List<List<Fruit>>
와 같은 중첩 리스트에서 자바와 비슷하게 flatMap
을 사용할 수 있다.// 중첩 리스트에서 현재가와 출고가가 같은 과일 필터링
val samePriceFruits = fruitsInList.flatMap { list ->
list.filter { it.factoryPrice == it.currentPrice }
}
data class Fruit( ... ) {
val isSamePrice: Boolean // 가격이 같은지 판별하는 커스텀 게터 구현
get() = factoryPrice == currentPrice
}
// List<Fruit>에 isSamePrice를 호출하는 확장 함수 구현
val List<Fruit>.samePriceFilter: List<Fruit>
get() = this.filter(Fruit::isSamePrice)
// 최종 형태
val samePriceFruits = fruitsInList.flatMap { it.samePriceFilter }
val fruits = fruitsInList.flatten()