Current location - Quotes Website - Signature design - What are the uses of the new feature lambda expression in Java 8?
What are the uses of the new feature lambda expression in Java 8?

Java 8 finally introduces lambda expressions, which marks another small step towards functional programming in Java.

In code before Java 8, in order to implement an interface with a method, it was often necessary to define an anonymous class and override the interface method, which made the code very bloated. For example, the common Comparator interface: String[]?oldWay?=?"Improving?code?with?Lambda?expressions?in?Java?8".split("?");

Arrays.sort( oldWay,?new?Comparator()?{

@Override

public?int?compare(String?s1,?String?s2)?{

//?Ignore case sorting:

return?s1.toLowerCase().compareTo(s2.toLowerCase());

}

});

System.out.println(String.join(",?",?oldWay));

For interfaces with only one method, in Java 8, now It can be regarded as a function, simplified with lambda expression as follows: String[]?newWay?=?"Improving?code?with?Lambda?expressions?in?Java?8".split("?");

Arrays.sort(newWay,?(s1,?s2)?->?{

return?s1.toLowerCase().compareTo(s2.toLowerCase());

});

System.out.println(String.join(",?",?newWay));

Java 8 does not introduce a new keyword lambda , but use the strange symbol ()->{} to represent the lambda function. The function type does not need to be declared and can be automatically deduced from the method signature of the interface. For the above lambda function: (s1,?s2)?->?{

return?s1.toLowerCase().compareTo( s2.toLowerCase());

});

The parameters are automatically derived from the String type by Comparator, and the return value must also conform to the method signature of the interface.

In fact, the lambda expression is eventually compiled into an implementation class, but the syntax is simplified.

For the large number of single-method interfaces in Java's own standard library, many have been marked @FunctionalInterface, indicating that the interface can be used as a function.

Take the Runnable interface as an example. In many cases, there is not as much work code as there is code for defining classes. Now it can be implemented using lambda: public?static?void?main(String[]?args)?{< /p>

//?old?way:

Runnable?oldRunnable?=?new?Runnable()?{

@Override

public ?void?run()?{

System.out.println(Thread.currentThread().getName()?+?":?Old?Runnable");

}

};

Runnable?newRunnable?=?()?->?{

System.out.println(Thread.currentThread().getName( )?+?":?New?Lambda?Runnable");

};

new?Thread(oldRunnable).start();

new ?Thread(newRunnable).start();

}

In future Java code, more and more ()->{} expressions will appear.