Last active
April 20, 2020 08:00
-
-
Save jickoo/7e82b370358680fcfa1ad5dd42bef7db to your computer and use it in GitHub Desktop.
sorting by LocalDateTime in List<Model.Map<String, Object>> #LocalDateTime #List #sort #정렬
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LocalDateTimeSorting { | |
public static void main (String... args) { | |
List<Model> list = new ArrayList<>(); | |
Model m = new Model(); | |
Map<String, Object> map = new HashMap<>(); | |
map.put("datetime", "2019-07-08 18:10:10.0"); | |
m.setMapInfo(map); | |
list.add(m); | |
Model m2 = new Model(); | |
Map<String, Object> map2 = new HashMap<>(); | |
map2.put("datetime", "2019-07-04 18:10:10.0"); | |
m2.setMapInfo(map2); | |
list.add(m2); | |
// add multiple Model in list | |
// list.size() > 2 | |
// list.sort need Comparator<? super E> c | |
// Comparator.comparing need | |
// Function<? super T, ? extends U> keyExtractor, | |
// Comparator<? super U> keyComparator | |
list.sort(Comparator.comparing( | |
it -> (String) it.getExtraInfoValue("datetime"), | |
(v1, v2) -> compare(v1, v2, "yyyy-MM-dd HH:mm:ss.S")) | |
); | |
System.out.println(m.getMapInfo.get("datetime")); // 2019-07-04 18:10:10.0 | |
} | |
public static int compare(String value1, String value2, String format) { | |
LocalDateTime d1 = LocalDateTime.parse(value1, DateTimeFormatter.ofPattern(format)); | |
LocalDateTime d2 = LocalDateTime.parse(value2, DateTimeFormatter.ofPattern(format)); | |
if (d1.isEqual(d2)) { | |
return 0; | |
} | |
return d1.isAfter(d2) ? 1 : -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment