我有复杂的对象
class Person{
Integer id;
String fname;
String lname;
//..... there are more attributes
List<Address> addresses;
}
class Address{
String street1;
String street2;
String city;
String state;
String zip;
}
我有 30000个人个对象,每个对象至少有 200-500个子对象(地址)。现在我有所有这些内存,我有不同的场景(20-30场景),我必须根据场景中可用的过滤器查询/过滤对象。例如。
简而言之,有两种情况,两种对象的组合不同。 请告知使用番石榴这种情况的最佳方法吗?
答案 0 :(得分:3)
您应该将Iterables.filter(Iterable, Predicate)
与Predicate
s。
示例:
public class PersonLastNameEqualsPredicate implements Predicate<Person> {
private String personName;
public PersonNameEqualsPredicate (String personName) {this.personName= personName;}
public boolean apply(Person p) { return this.personName.equals(p.getLName()); }
}
public class PersonStreet1EqualsPredicate implements Predicate<Person> {
private String street1Name;
public PersonStreet1EqualsPredicate (String street1Name) {this.street1Name = street1Name;}
public boolean apply(Person p) {
for (Address a: p.getAddresses()) {
if (street1Name.equals(a.getStreet1()) return true;
}
return false;
}
}
// Extra predicates as you need them
每个方案项需要一个谓词。然后你需要根据需要调整它们:
1
Predicate<Person> peopleNamedZoik = new PersonLastNamePredicate("zoik");
2
Predicate<Person> peopleNamedSmarkAndLivingInXyzStreet = Predicates.and(new PersonLastNamePredicate("smark"), new PersonStreet1EqualsPredicate("xyz"));
3
在这里,您应该调整街道谓词,以便立即检查所有街道名称是否包含您的所有期望。
然后它只是
的问题1
List<Person> myLongPersonList = ...;
Iterable<Person> zoikPeople = Iterables.filter(myLongPersonList, peopleNamedZoik);
2
List<Person> myLongPersonList = ...;
Iterable<Person> zoikPeople = Iterables.filter(myLongPersonList, peopleNamedSmarkAndLivingInXyzStreet);
等等。