简体   繁体   中英

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 ?

With Java 8 you can achieve this with a stream filter:

List<CustomObject> collect = existingValues.stream()
.filter(object -> ids.contains(object.getId()))
.collect(Collectors.toList());

To get familiar with java streams I recommand the offical Oracle Tutorial .

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

Yes as @wuethrich44 says in Java 8 the solution is:

List<CustomObject> collect = existingValues.stream()
    .filter(object -> ids.contains(object.getId()))
    .collect(Collectors.toList());

And in the case you have a version older than Java 8:

List<CustomObject> collect = new ArrayList<CustomObject>();
for(CustomObject object: existingValues) {
    if(ids.contains(object.getId())) {
        collect.add(object);
    }
}

And for version older than Java 5:

List<CustomObject> collect = new ArrayList<CustomObject>();
Iterator<CustomObject> iterator = existingValues.iterator();
while(iterator.hasNext()) {
    CustomObject object = iterator.next();
    if(ids.contains(object.getId())) {
        collect.add(object);
    }
}

but the version with stream is better: faster in term of execution time, less verbose, and more readable if you are use to it

如果可以使用我的xpresso库,则可以将列表推导与lambda表达式一起使用,如下所示:

list<CustomObject> filtered = x.list(x.<CustomObject>yield().forEach(existingValues).when(x.lambdaP("x : f1(f0(x))",x.invoke("getId"),x.in(ids))));

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