Suppose I have a class (response model)
TransactionResult {
private List<Transaction> transactions;
}
Transaction {
private OffsetDateTime date;
private String account;
}
and I want to have unique transactions by account and should be the newest by date. So, I have mapped dto
TransactionResultDto {
private Set<TransactionDto> transactions;
}
TransactionDto implements Comparable<TransactionDto> {
private OffsetDateTime date;
private String account;
//equals and hashcode only using account
//compareTo using date
}
Firstly, I collect into a TreeSet to sort the transactions (newest are first) and then I build a HashSet to have unique transactions by account.
Set<TransactionDto> transactions = new HashSet<>(
transactionResult.getTransactions().stream()
.map(transaction -> mapToTransactionDto(transaction))
.collect(Collectors.toCollection(TreeSet::new)));
So, the questions are:
- Is this the right way to collect the newest and unique by account transactions?
- Do you have any improvements or other ideas?