Sunday, 9 August 2015

Guava: Function interface


By using Function interface, you can introduce some functional programming into your java application. Function interface has two methods apply and equals.

apply: Performs some calculations on input and return some output.
equals: Indicates whether another object is equal to this function.

public interface Function<F, T> { 
  @Nullable T apply(@Nullable F input);

  @Override
  boolean equals(@Nullable Object object);
}

Note
a.   If Object A equals Object B, the result of calling apply on A should equal the result of calling apply on B.
b.   For a good Function interface implementation, the object passed as an argument should remain unchanged after the apply method has been called.

import com.google.common.base.Function;
import com.google.common.base.Preconditions;

public class FunctionEx {

  public static Function<Integer[], Integer> minElement = new Function<Integer[], Integer>() {

    @Override
    public Integer apply(Integer[] input) {
      Preconditions.checkNotNull(input, "Input array shouldn't be null");
      int min = Integer.MAX_VALUE;

      for (int val : input) {
        if (val < min) {
          min = val;
        }
      }

      return min;
    }

  };

  public static Function<Integer[], Integer> maxElement = new Function<Integer[], Integer>() {

    @Override
    public Integer apply(Integer[] input) {
      Preconditions.checkNotNull(input, "Input array shouldn't be null");
      int max = Integer.MIN_VALUE;

      for (int val : input) {
        if (val > max) {
          max = val;
        }
      }

      return max;
    }

  };

  public static void main(String args[]) {
    Integer[] arr = { 2, 3, 5, 7, 1, 3, 8, 9, 10 };

    System.out.println("Minimum element is " + minElement.apply(arr));
    System.out.println("Maximum element is " + maxElement.apply(arr));
  }
}


Output
Minimum element is 1
Maximum element is 10



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment