my pochta
my pochta

Reputation: 13

How to compare two list?

I have two lists, I would like to compare them with each other and introduce differences, but my code does not work, what could be the problem? How would you do that?

private List<Payment> rbsList;
private List<Payment> partnerList;

public void compare() {
    try {
        for (Payment rbs : rbsList) {
            for (Payment partner : partnerList) {
                if (partner.getAccount().equals(rbs.getAccount()) && partner.getSum() == rbs.getSum()) {
                    rbs.setExist(true);
                    partner.setExist(true);
                }
            }
        }
    } catch (OutOfMemoryError | ConcurrentModificationException exception) {
        exception.printStackTrace();
    }

    notMatchedRBS = rbsList.stream().filter(r -> !r.isExist()).collect(Collectors.toList());
    notMatchedPartner = partnerList.stream().filter(p -> !p.isExist()).collect(Collectors.toList());

}

Upvotes: 0

Views: 118

Answers (2)

Tal Glik
Tal Glik

Reputation: 510

  1. In payment class, add implementation for equals() then you can just do: partner.equals(rbs) in the if.

  2. Consider using Java stream instead of the two for loops:

         List<Payment> differences = rbsList.stream()
             .filter(element -> !partnerList.contains(element))
             .collect(Collectors.toList());
    

Upvotes: 0

Martin Capparelli
Martin Capparelli

Reputation: 21

The code seems to be ok. It's Important to define what equals means to you, let's say:

-> Two accounts are equals if both has the same Id.

I recommend you to check if Account's equals is properly defined. The same happens with getSum().

Upvotes: 1

Related Questions