番石榴 - 按属性和包含过滤

时间:2015-01-13 19:30:02

标签: java collections filter guava

我试图通过对象中的多个属性进行过滤,在我的情况下是CarObj:

    List<String> colorList = (List<String>)filterCriteria.get("Color");
    List<String> makeList = (List<String>)filterCriteria.get("Make");
    List<String> rimSizeList = (List<String>)filterCriteria.get("RimSize");

    Predicate<String> predColor = Predicates.in(ImmutableSet.copyOf(colorList));
    Predicate<CarObj> predColor2 = Predicates.compose(predColor ,[????] );

    Predicate<String> predMakeList  = Predicates.in(ImmutableSet.copyOf(makeList));
    Predicate<CarObj> predMakeList2 = Predicates.compose(predMakeList, [????] );

    Predicate<String> predRimSize = Predicates.in(ImmutableSet.copyOf(rimSizeList));
    Predicate<CarObj> predRimSize2 = Predicates.compose(predRimSize, [????] );

    Collection<CarObj> filtered = FluentIterable.from(mAllCars)
            .filter(predColor2)
            .filter(predMakeList2)
            .filter(predRimSize2)
            .toList();

如何输入逻辑来处理StartsWith或Contains功能? 因此,如果用户输入“Silver”并且在我的CarObjs集合中,Model属性具有“Silverado”,“Silverline”,“Silverpig”,“Tacoma”,“Accord”等...

我想找到一种过滤方法,以便返回以“Silver”开头的汽车。它将返回所有型号为Silverado,Silverline或Silverpig的汽车,满足其他3个过滤器,颜色,轮辋尺寸和制作

1 个答案:

答案 0 :(得分:2)

在Java 8中,你可以写

Predicate<CarObj> predColor2 = Predicates.compose(predColor , CarObj::getColor);

但是否则你必须写

Predicate<CarObj> predColor2 = Predicates.compose(predColor , 
   new Function<CarObj, String>() {
     @Override public String apply(CarObj car) {
       return car.getColor();
     }
   });

如果您想按以下方式过滤: startsWith,然后不要使用Predicates.compose,而是写

final Set<String> makes = ImmutableSet.copyOf(makeList);
Predicate<CarObj> predMake2 = new Predicate<CarObj>() {
  @Override public boolean apply(CarObj car) {
    for (String make : makes) {
      if (car.getMake().startsWith(make)) {
        return true;
      }
    } 
    return false;
  }
};