简体   繁体   中英

How to compare a field between two Lists of objects?

Let's suppose I've an object that looks like this:

public class Supermarket {

    public String supermarketId;
    public String lastItemBoughtId;

    // ...
}

and I have two lists of supermarkets, one "old", another "new" (ie one is local, the other is retrieved from the cloud).

List<Supermarket> local = getFromLocal();
List<Supermarket> cloud = getFromCloud();

I would like to find all the pairs of Supermarket objects (given supermarketId ) that have lastItemBoughtId different from one another.

The first solution I have in mind is iterating the first List , then inside the first iteration iterating the second one, and each time that local.get(i).supermarketId.equals(cloud.get(j).supermarketId) , checking if lastItemBoughtId of the i element is different from the id of the j element. If it's different, I add the whole Supermarket object on a new list.

To be clearer, something like this:

List<Supermarket> difference = new ArrayList<>();
for (Supermarket localSupermarket : local) {
    for (Supermarket cloudSupermarket : cloud) {
        if (localSupermarket.supermarketId.equals(cloudSupermarket.supermarketId) &&
        !localSupermarket.lastItemBoughtId.equals(cloudSupermarket.lastItemBoughtId))
            difference.add(cloudSupermarket);
    }
}

Clearly this looks greatly inefficient. Is there a better way to handle such a situation?

One solution :

  1. Construct a Map of the Local supermarkets using the supermarketId as the key by running through the list once
  2. Loop through the cloud list and do you comparison, looking up the local supermarket from your map.

ie O(n) instead of O(n 2 )

Here's a two-line solution:

Map<String, Supermarket> map = getFromLocal().stream()
    .collect(Collectors.toMap(s -> s.supermarketId, s -> s));
List<Supermarket> hasDiffLastItem = getFromCloud().stream()
    .filter(s -> !map.get(s.supermarketId).lastItemBoughtId.equals(s.lastItemBoughtId))
    .collect(Collectors.toList());

我会将其中一个列表放在Map ,将Supermarket ID作为关键字,并将Supermarket实例的值作为键,然后遍历另一个从Map获取并比较lastItemBoughtId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM