Java Stream How to - Compare the method reference








Question

We would like to know how to compare the method reference.

Answer

//from w  w w .j  av a 2s  .co  m
public class Main {

    Add addable = (a, b) -> a+b;
    Add addableViaMethodReference = this::addThemUp;
    Add addableViaMethodReference2 = Integer::sum;
    Add addableViaMethodReference3 = StaticUtil::addThemUp;
    Add addableViaMethodReference4 = new Util()::addThemUp;

  
    private int addThemUp(int i1, int i2){
        return i1*i2;
    }
    public void add(int i1, int i2){
        System.out.println("Sum of two numbers using lambda: "+addable.add(i1, i2));
        System.out.println("Sum using Method Reference to a local method: "+addableViaMethodReference.add(i1, i2));
        System.out.println("Sum using references to a someother type's method: "+addableViaMethodReference2.add(i1, i2));
        System.out.println("Sum of two numbers some other object's method: "+addableViaMethodReference3.add(i1, i2));
        System.out.println("Sum of two numbers some other object's method: "+addableViaMethodReference4.add(i1, i2));
    }
    public static void main(String[] args) {
        Main test = new Main();
        test.add(100, 200);
    }    
}

@FunctionalInterface
interface Add {
   int add(int t1, int t2);
}
class StaticUtil {
  
  public static int addThemUp(int i1, int i2){
      return i1+i2;
  }
}

class Util {
    
    public int addThemUp(int i1, int i2){
        return i1+i2;
    }
}

The code above generates the following result.