0

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?

fashuser
  • 2,152
  • 3
  • 29
  • 51
  • 1
    This isn't an answer since you're asking about lamdaj and guava, but really you only need a single loop through the CustomObject List, then using contains to see if the Id is in the Set. Assuming it's a HashSet, those will be constant-time lookups. – jas May 06 '15 at 07:51

4 Answers4

1

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.

fabwu
  • 642
  • 6
  • 19
1

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();
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
0

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

kwisatz
  • 1,266
  • 3
  • 16
  • 36
0

If you can use my xpresso library you can use list comprehensions with lambda expressions like this:

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