Search code examples
javaguavalambdaj

Find intersection between collections with different objects


I have list of custom objects like below:

List<CustomObject> existingValues

And another collection with ids that has been sent from client and contains ids of CustomObject mentoioned above Set<Long> ids.

My goal is to return collection with CustomObject that will contains only elements where ids intersect.

I can simply do this with nested for each cycles. But it looks a bit ugly.

In SQL I can do similar stuff with query:

select * where customobject.id in (some ids...)

In wich way it can be achived with lamdaj or guava?


Solution

  • With Guava this is done as follows:

        final Set<Long> ids = ...; //initialize correctly
    
        List<CustomObject> results = FluentIterable.from(existingValues).filter(new Predicate<CustomObject>() {
            @Override
            public boolean apply(final CustomObject input) {
                return ids.contains(input.getId());
            }
        }).toList();