Created
November 3, 2022 08:37
-
-
Save limboinf/5b0cd54e25b6d71b8b909a08e3e65627 to your computer and use it in GitHub Desktop.
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
// group by traceId, event fields and get the max item. | |
void testIt() { | |
List<Event> events = new ArrayList<>(); | |
events.add(new Event("AAA", "ROOM_START", 1000L, 10)); | |
events.add(new Event("AAA", "ROOM_START", 1000L, 10)); | |
events.add(new Event("BBB", "ROOM_START", 1002L, 15)); | |
events.add(new Event("BBB", "ROOM_START", 1001L, 10)); | |
// method1 | |
Map<String, Map<String, List<Event>>> collect = events.stream() | |
.collect(Collectors.groupingBy(Event::getTraceId, Collectors.groupingBy(Event::getEvent))); | |
collect.forEach((traceId, mp) -> { | |
mp.forEach((event, ls) -> { | |
System.out.printf("\t traceId=%s, event=%s, mp=%s\n", traceId, event, JSON.toJSONString(ls)); | |
Event last = ls.stream().sorted(Comparator.comparing(Event::getLocalTs).reversed()).findFirst().orElse(null); | |
System.out.printf("\t last: %s\n", last); | |
}); | |
}); | |
// method 2 | |
Function<Event, List<String>> compositeKey = event -> Arrays.asList(event.getTraceId(), event.getEvent()); | |
Map<List<String>, List<Event>> listMap = events.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList())); | |
listMap.forEach((g, ls) -> { | |
Event last = ls.stream().sorted(Comparator.comparing(Event::getLocalTs).reversed()).findFirst().orElse(null); | |
System.out.printf("\t last: %s\n", last); | |
}); | |
// method 3 | |
List<Event> rs = new ArrayList<>(); | |
events.stream() | |
.collect(Collectors.groupingBy(Event::getTraceId, Collectors.groupingBy(Event::getEvent))) | |
.forEach((traceId, mp) -> { | |
mp.forEach((event, ls) -> { | |
Optional<Event> lastOpt = ls.stream().max(Comparator.comparing(Event::getLocalTs)); | |
lastOpt.ifPresent(rs::add); | |
}); | |
} | |
); | |
System.out.println(JSON.toJSONString(rs)); | |
// method 4 | |
List<Event> rs2 = new ArrayList<>(); | |
Function<Event, List<String>> gKey = event -> Arrays.asList(event.getTraceId(), event.getEvent()); | |
events.stream().collect(Collectors.groupingBy(gKey, Collectors.toList())) | |
.forEach((g, ls) -> { | |
Optional<Event> lastOpt = ls.stream().max(Comparator.comparing(Event::getLocalTs)); | |
lastOpt.ifPresent(rs2::add); | |
}); | |
System.out.println(JSON.toJSONString(rs2)); | |
} | |
@Data | |
@AllArgsConstructor | |
static class Event { | |
private String traceId; | |
private String event; | |
private Long localTs; | |
private Integer duration; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment