Java8 lambda & prediction

Java8 lambda and prediction examples,

To filter a list of elements we can use previous version of java as follows..

color picker ..
public static List filterApple(List apples, String color) {
  List list = new ArrayList<>();
  for (int i = 0; i < apples.size(); i++) {
     if (color.equals(apples.get(i).getColor())){
         list.add(apples.get(i));
      }
    }
    return list;
 }

weight picker..
public static List filterApple(List apples, int weight) {
   List list = new ArrayList<>();
   for (int i = 0; i < apples.size(); i++) {
     if (weight == apples.get(i).getWeight())){
        list.add(apples.get(i));
      }
   }
   return list;
 }

Instead of this. we can use prediction for simpler and for more different filter options.

For example consider this example..

 public static List<Apple> filterApple(List<Apple> apples, ApplePredicate p) {
   List<Apple> list = new ArrayList<>();
   for (int i = 0; i < apples.size(); i++) {
      if (p.test(apples.get(i))) {
         list.add(apples.get(i));
      }
    }
    return list;
 }

A prediction type to be passed as an argument to the filter method so that what kind of filter options is that we can still use it in a single method instead of multiplying the same code over and over again..

In addition to this we can use prediction list to pass as and argument as well and so that if we can use this list to filter object with more details. Such as an apple  , red , green, heavy, light.

 

 List<ApplePredicate> predicates = new ArrayList<>();
 predicates.add(new ApplePredicateGreen());
 predicates.add(new ApplePredicateHeavy());
 
 System.out.println("heavy and green with a list of predicates");
 List<Apple> heavyAndGreenList = filterApple(apples, predicates);
 System.out.println(heavyAndGreenList); 

public static List<Apple> filterApple(List<Apple> apples, List<ApplePredicate> predicates) {
   List<Apple> list = new ArrayList<>();
   for (int i = 0; i < apples.size(); i++) {
     boolean found = true;
     for(ApplePredicate p: predicates){
       if (! p.test(apples.get(i))) {
         found = false;
         break;
       }
     }
     if(found){
       list.add(apples.get(i));
     }
   }
   return list;
 }

 

#Note

Reklamlar

Bir Cevap Yazın

Aşağıya bilgilerinizi girin veya oturum açmak için bir simgeye tıklayın:

WordPress.com Logosu

WordPress.com hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap / Değiştir )

Twitter resmi

Twitter hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap / Değiştir )

Facebook fotoğrafı

Facebook hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap / Değiştir )

Google+ fotoğrafı

Google+ hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap / Değiştir )

Connecting to %s