Based on the clarifications you've given in the comments I've used a LocalDateTime
to simplify the sample entry and retrieve the hour, but I'm sure that google.protobuf.Timestamp
can be converted to a proper date and extract its hour.
To keep only one object according to description, date and hour, I've added a helper method to your POJO to get a concatenation of these fields and then group by their result value in order to get a Map
where to each key (description, date and hour) there is only one object associated. Lastly, I've collected the Map
's values into a List
.
List<MyObject> list = new ArrayList<>(List.of(
new MyObject(LocalDateTime.parse("06-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
new MyObject(LocalDateTime.parse("06-07-2022T01:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
new MyObject(LocalDateTime.parse("06-07-2022T03:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
new MyObject(LocalDateTime.parse("06-07-2022T04:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
new MyObject(LocalDateTime.parse("06-07-2022T04:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
new MyObject(LocalDateTime.parse("06-07-2022T06:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
new MyObject(LocalDateTime.parse("08-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description")
));
List<MyObject> listRes = list.stream()
.collect(Collectors.toMap(
obj -> obj.getDescrDateHour(),
Function.identity(),
(obj1, obj2) -> obj1
))
.values()
.stream().
collect(Collectors.toList());
POJO Class
class MyObject {
private LocalDateTime timestamp;
private String description;
public MyObject(LocalDateTime timestamp, String description) {
this.timestamp = timestamp;
this.description = description;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public String getDescription() {
return description;
}
public String getDescrDateHour() {
return description + timestamp.toLocalDate().toString() + timestamp.getHour();
}
@Override
public String toString() {
return timestamp + " - " + description;
}
}
Here is a link to test the code
https://www.jdoodle.com/iembed/v0/sZV
Output
Input:
2022-07-06T01:30 - some random description
2022-07-06T01:35 - some random description
2022-07-06T03:20 - some random description
2022-07-06T04:30 - some random description2
2022-07-06T04:35 - some random description2
2022-07-06T06:20 - some random description2
2022-07-08T01:30 - some random description
Output:
2022-07-06T04:30 - some random description2
2022-07-08T01:30 - some random description
2022-07-06T06:20 - some random description2
2022-07-06T03:20 - some random description
2022-07-06T01:30 - some random description