728x90
데이터 필터링 작업을 하던 중에 조금 특수한 케이스를 처리해야 하는 상황이 생겨 몇 가지 컬렉션 함수를 실무에서 사용했습니다.
어떤 boolean 값으로 구분이 가능한 데이터 리스트가 존재하고, 이 중 false인 부분을 다시 특정 날짜값에 의해 그룹화하여 어떤 필드의 최대 값을 가지고 있는 요소만 살리도록 하는.. 그런 로직이 필요했습니다.
일단 먼저 boolean 값 구분을 위해 partition 함수를 사용했습니다. 명시한 조건에 따라 리스트를 분리해 줍니다.
저는 true/false 조건이기 때문에 변수 2가지로 리스트를 구분할 수 있었습니다.
val (fineDatas, nonFineDatas) = allDatas.partition { it.isFine() }
다음으로 nonFineDatas를 it.dtTime 이라는 날짜 데이터를 가진 필드를 기준으로 Map을 구성하겠습니다.
val testLists = nonFineDatas
.groupBy { it.dtTime }
it.dtTime을 키로, 해당하는 DataList를 값으로 가지는 Map이 구성됩니다.
이제 이 Map을 다시 cnt라는 필드를 최대 값으로 가지고 있는 데이터들만 골라내어 List로 변환합니다.
마지막에 null 값을 Clear해주도록 filterNotNull()까지 호출해 주었습니다.
val testLists = nonFineDatas
.groupBy { it.dtTime }
.map { (_, values) -> values.maxByOrNull { it.cnt } }
.filterNotNull()
이렇게 목표했던 데이터 정리 로직이 완료되었네요..
728x90