Monday, June 09, 2014

What's New in Java 8 - Method References

Method references provide easy-to-read lambda expressions for methods that already have a name.
We have seen lambda expressions to crate anonymous methods in my post What's New in Java 8 - Lambda Expressions. Sometimes a lambda expression does nothing but call an existing method (will see example in detail). In those cases, we use method references instead lambda expressions. Method references are compact and easy to read lambda expressions for methods that already have a name.

Example  :

To better understand, consider the same car example discussed in my previous post, but here a extra compareByEngineCC static method.

public class Car{
    public enum Color {
        BLACK, WHITE, RED
    }
    public String modelName;
    public Color color;
    public int engineCC;
    public void printModelName() {
        // ...
    }
    
    public static int compareByEngineCC(Car c1, Car c2) {
        if( c1.engineCC  == c2.engineCC) return 0;
        return c1.engineCC > c2.engineCC?1:-1;
    }
}

The requirement is sort the array of cars by engineCC, so that I added a static method to  compare the cars.
We can use sort method which is static in Arrays class to meat this requirement, but in order to use this static method we need to provide Comparator, So we implemented a CarEngineCCComparator class as shown below

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...