Home > Mobile >  How to compare two list?
How to compare two list?

Time:11-10

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());

}

CodePudding user response:

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().

CodePudding user response:

  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());
    
  •  Tags:  
  • java
  • Related