简体   繁体   English

Java中两个列表的交集

[英]Intersections of two lists in java

I have used for and if loop to find intersections of list by comparing its inners JSON. 我已经使用for和if循环通过比较列表的内部JSON来查找列表的交集。 I am looking for the solution using CollectionUtils or Java 8 or some other similar solution. 我正在寻找使用CollectionUtils或Java 8或其他类似解决方案的解决方案。

private List<IBXLocation> compareIbxLocationDetails(List<IBXLocation> serviceIbxsForLoggedInUser,
        List<IBXLocation> serviceIbxsForUser) {
    List<IBXLocation> finalList=new ArrayList();
    for (IBXLocation ibxForLoggedInUser : serviceIbxsForLoggedInUser) {
        String ibxSelected=ibxForLoggedInUser.getIbx();
        boolean ibxFound = false;
        ibxLoop:for (IBXLocation permittedIBXForUser : serviceIbxsForUser) {
            if (ibxSelected.equals(permittedIBXForUser.getIbx())) {
                IBXLocation newIbx = new IBXLocation(ibxSelected);
                List<Cage> newCageList=new ArrayList();
                if (!CollectionUtils.isEmpty(ibxForLoggedInUser.getCageDetails())) {
                    for (Cage selectedCage : ibxForLoggedInUser.getCageDetails()) {
                        String loggedInSelectedCageStr = selectedCage.getCage();
                        for (Cage permittedCage : permittedIBXForUser.getCageDetails()) {
                            if (loggedInSelectedCageStr.equals(permittedCage.getCage())) {
                                newCageList.add(permittedCage);
                            }

                        }
                        newIbx.setCageDetails(newCageList);
                    }
                    finalList.add(newIbx);
                }
                ibxFound = true;
                break ibxLoop;
            }

        }

    }

    return finalList;
}

You can use this 你可以用这个

Set ibxForLoggedInUserToSet= new HashSet<IBXLocation>(ibxForLoggedInUser);

for(IBXLocation per: serviceIbxsForUser){
     if (ibxForLoggedInUserToSet.contains(per)){
          finalList.add(per);
     }
}

org.apache.commons.collections4.ListUtils有一个方法public static <E> List<E> intersection(List<? extends E> list1, List<? extends E> list2)

You can utilize Set to get intersections: 您可以利用Set获得相交:

public <T> intersect(List<T> firstList, List<T> secondList) {
     Set<T> result = new HashSet<>();
     result.addAll(firstList);
     result.addAll(secondList);
     return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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