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