Find intersection in multiple lists

Igor :

Apologies if this was asked before but I couldn't find anything that would be similar to my problem. So what I have is a list of objects that contains an ArrayList of values.

For example:

public class MyClass {
    List<Long> bets = new ArrayList<>();
    ....
}

List<MyClass> myClassList = currencyMap.get(currencyCode);

I've been trying something but I believe my solution is somewhat not ok:

for (int i = 0; i < myClassList.size(); i++) {
    if (i + 1 >= myClassList .size()) {
        break;
    }
    myClassList.get(i).getBets().retainAll(myClassList.get(i + 1).getBets());
}

So what I would like to do now is to find intersection on all bets lists in MyClass list.

Andronicus :

You can use reduce for that:

myClassList.stream()
    .map(MyClass::getBets)
    .reduce((l1, l2) -> l1.stream()
        .filter(l2::contains)
        .collect(Collectors.toList()))
    .orElse(new ArrayList<Long>());

The reduce operation takes two consecutive lists and produces an intermediate one with elements, that are in both original lists.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371633&siteId=1