Remove Duplicates With Stream Distinct

Viewed 107
  @Override
    public List<ExpenseListingDTO> getExpenseListByServiceFileId(Long serviceFileId) {

        if (Long.valueOf(serviceFileId) != null) {
            List<ExpenseListDetail> expenseListDetail = expenseListDetailRepository.findByServiceFileId(serviceFileId);
            List<ExpenseList> expenseList = expenseListRepository.findByExpenseListDetailListIn(expenseListDetail);
            //
            List<ExpenseListingDTO> expenseListDtoList = expenseListMapper.expenseListDTOToExpenseListingDTO(expenseListMapper.entityListToDtoList(expenseList));
            expenseListDtoList.parallelStream().forEach(dto -> {
                dto.setTotalAmount(
                        expenseListDetail.stream().filter(s -> s.getOperationType().equals(OperationType.NEW_EXPENSE.getValue()) || s.getOperationType().equals(OperationType.EXPENSE_RETURN.getValue()))
                                .filter(s -> !s.getStatus().equals(ExpenseListDetailStatus.PASSIVE.getValue())).map(ExpenseListDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));

            });
            return expenseListDtoList.stream()
                    .distinct()
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

This function returns a list. But there ara some same lists on my output. I want to remove duplicates. But it didn't work. What is the problem in here?

1 Answers

Please take a look and implement the ExpenseListingDTO#equals and ExpenseListingDTO#hashCode methods. If ExpenseListingDTO objects are the same, these methods should reflect this.

EDIT: As request by the comments, a guide to overwrite these my be found here.

public class ExpenseListingDTO {

....

@Override
public boolean equals(Object o) {

    // If the object is compared with itself then return true 
    if (o == this) {
        return true;
    }

    /* Check if o is an instance of ExpenseListingDTO or not
      "null instanceof [type]" also returns false */
    if (!(o instanceof ExpenseListingDTO)) {
        return false;
    }
     
    // typecast 
    ExpenseListingDTO expenseListingDTO = (ExpenseListingDTO) o;
     
    // compare other member variables, etc...
    return this.XX == expenseListingDTO.XXX;
}
}
Related