날짜 형식을 가진 문자열을 정렬하는 방법을 정리합니다.
리스트 정렬 방법으로 sortWith 를 활용합니다.
1. sortWith 활용
val dateList = ArrayList<String>()
dateList.add("2022-04-01 01:10")
dateList.add("2022-04-03 03:11")
dateList.add("2022-04-03 02:10")
dateList.add("2022-04-02 01:10")
dateList.add("2022-04-03 03:10")
dateList.add("2022-04-03 03:12")
dateList.add("2022-02-01 01:10")
dateList.add("2022-04-03 01:10")
Log.d("[TEST]", "Before sorted")
for (date in dateList) {
Log.d("[TEST]", date)
}
dateList.sortWith { o1, o2 ->
o2.compareTo(o1) // Reverse : o1.compareTo(o2)
}
Log.d("[TEST]", "After sorted")
for (date in dateList) {
Log.d("[TEST]", date)
}
2. 실행 결과
D/[TEST]: Before sorted
D/[TEST]: 2022-04-01 01:10
D/[TEST]: 2022-04-03 03:11
D/[TEST]: 2022-04-03 02:10
D/[TEST]: 2022-04-02 01:10
D/[TEST]: 2022-04-03 03:10
D/[TEST]: 2022-04-03 03:12
D/[TEST]: 2022-02-01 01:10
D/[TEST]: 2022-04-03 01:10
D/[TEST]: After sorted
D/[TEST]: 2022-04-03 03:12
D/[TEST]: 2022-04-03 03:11
D/[TEST]: 2022-04-03 03:10
D/[TEST]: 2022-04-03 02:10
D/[TEST]: 2022-04-03 01:10
D/[TEST]: 2022-04-02 01:10
D/[TEST]: 2022-04-01 01:10
D/[TEST]: 2022-02-01 01:10
0 comments: