Guava - Function and Predicate, Optional


The Predicate interface is used to filter objects.

public static Iterable<VendorItemPackageImage> filterImages(List<VendorItemPackageImage> packageImages, VendorItemPackageImageType type) {
   Predicate<VendorItemPackageImage> predicate = new HighLevelTypePredicate(type);
   return  Iterables.filter(packageImages, predicate);
}

static class HighLevelTypePredicate implements Predicate<VendorItemPackageImage> {
   private VendorItemPackageImageType type;
   public HighLevelTypePredicate(VendorItemPackageImageType type) {
      this.type = type;
   }
   public boolean apply(VendorItemPackageImage image) {
      return image.getVendorItemPackageImageType().getHighLevelImageType().equals(type);
   }
}

Reffering link: http://stackoverflow.com/questions/9520073/how-to-do-filter-query-on-in-memory-list-map-using-guava


The Function interface is used to transform objects.

public List<ImageInfo> transform(List<Image> images) {
   return Lists.transform(images, new Function<Image, ImageInfo>() {
      @Nullable @Override public ImageInfo apply(Image input) {
         VendorItemPackageImageInfo imageInfo = new ImageInfo();
         imageInfo.setId(input.getId());
         imageInfo.setImageOrder(input.getImageOrder());
         imageInfo.setImageType(input.getImageType());
         imageInfo.setPath(input.getPath);
         return imageInfo;
      }
   }
   );
}

Optional

The true importance of the Optional class is that it signals a value is not guaranteed to be present, and it forces us to deal with that fact.

List<YourObject> objs = Optional.fromNullable(some.getYourObjs()).or(new ArrayList<YourObject>());







你可能感兴趣的:(Guava - Function and Predicate, Optional)