Retrieving objects from list <X> based on some other collection of list properties

I have a class -

public class Data implements Identifiable{
    private Integer id;

    public Integer getId(){
        return id;
    }
}

now I have two collections -

List<Data> data1 = // few hundred Objects

Set<Integer> dataIds = // few object ids

I would like to extract List<Data>from data1which has identifiers indataIds

What should be my approach? Iva guava in my class, so you can go with guava Functional approach, if it is comparable in performance / efficiency.

+5
source share
3 answers

, , , , , , . List Set , - !

List<Data> result = Lists.newArrayList();
for (Data data : data1) {
  if (dataIds.contains(data.getId()))
    result.add(data);
}

, Data Identifiable. , Function<Identifiable, Integer>, ... Identifiables.getIdFunction() - . , , , ( ). Guava :

Predicate<Identifiable> predicate = Predicates.compose(
    Predicates.in(dataIds), Identifiables.getIdFunction());
List<Data> filtered = Lists.newArrayList(Iterables.filter(data1, predicate));

, , , . ( , ), , .

+3

Collections2.filter(
    data1,
    new Predicate<Data>() {
       public boolean apply(Data d) {
         return dataIds.contains(d.getId());
       }
    }
)

p.s. , , .

+3

With LambdaJ you can write:

List<Data> result = extract(data1, on(Data.class).getId());
0
source

All Articles