I have Documents
objects which I want to group by document ID. After grouping them, I want to get their "maximum". This is what I have so far:
List<Document> docList = getDocuments(...);
Map<Long, Document> docIdsToLatestDocVersions = docList.stream()
.collect(Collectors.groupingBy(
Document::getDocumentId,
Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing( Function.identity() ))
));
The Document class:
class Document {
int documentId;
int majorVersion;
int minorVersion;
@Override
public int compareTo(Document document) {
return new CompareToBuilder()
.append(this.getDocumentId(), document.getDocumentId())
.append(this.getMajorVersion(), document.getMajorVersion())
.append(this.getMinorVersion(), document.getMinorVersion())
.toComparison();
}
}
Importantly, I already have a compareTo function implemented. I'm not sure what to put in my reducer
argument of the groupingBy
clause. I also tried:
Map<Long, Document> docIdsToLatestDocVersions = docList.stream()
.collect(Collectors.toMap(
Document::getDocumentId, Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(d -> d))));
but to no avail.