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
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.