Android/Kotlin
[Android][Kotlin] 리스트 정렬 sortedBy(), sortedWith() 차이
yoo.o
2020. 8. 21. 04:26
반응형
페어(Pair) 리스트를 사용하다가 정렬하는 법을 찾아봤다.
sortedBy()
원본 리스트를 바꾸지 않고 소팅된 리스트를 리턴한다.
selector을 지정하면 소팅 기준을 정할 수 있다.
페어를 사용할때도 하나의 기준을 두고 정렬하고싶을때 사용하면 된다.
pair에 접근할땐 it.first it.second 이런식으로 하면 된다
var sorted = planedit.sortedBy{it.first}
내림차순으로 정렬할땐 sortedByDescending()을 사용하면 된다.
sortedWith()
역시 원본 리스트를 바꾸지 않고 소팅된 리스트를 리턴한다.
sortedBy()와 다른점은 comparator을 지정해서 다중 기준을 둘 수 있다는 점이다.
첫번째꺼로 먼저 소팅한 후, 두번째꺼로도 소팅을 할 수 있다는 것이다.
var sorted = planedit.sortedWith(compareBy({ it.first }, { it.second }))
[(0,2), (1,0), (0,0), (0,3), (0,1)] 을 위 코드로 소팅한 결과
[(0,0), (0,1), (0,2), (0,3), (1,0)] 이렇게 나온다!
내림차순으로 바꾸기 위해서는 reversed()를 써주면 된다.
var sorted = planedit.sortedWith(compareBy({ it.first }, { it.second })).reversed()
반응형