java 8 is a major feature release of java programming language development. its initial version was released on 18 march 2014. with the java 8 release, java provided supports for functional programming, new javascript engine, new apis for date time manipulation, new streaming api, etc.
new features
lambda expression − adds functional processing capability to java.
method references − referencing functions by their names instead of invoking them directly. using functions as parameter.
default method − interface to have default method implementation.
new tools − new compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.
stream api − new stream api to facilitate pipeline processing.
date time api − improved date time api.
optional − emphasis on best practices to handle null values properly.
nashorn, javascript engine − a java-based engine to execute javascript code.
consider the following code snippet.
import java.util.collections; import java.util.list; import java.util.arraylist; import java.util.comparator; public class java8tester { public static void main(string args[]) { list<string> names1 = new arraylist<string>(); names1.add("mahesh "); names1.add("suresh "); names1.add("ramesh "); names1.add("naresh "); names1.add("kalpesh "); list<string> names2 = new arraylist<string>(); names2.add("mahesh "); names2.add("suresh "); names2.add("ramesh "); names2.add("naresh "); names2.add("kalpesh "); java8tester tester = new java8tester(); system.out.println("sort using java 7 syntax: "); tester.sortusingjava7(names1); system.out.println(names1); system.out.println("sort using java 8 syntax: "); tester.sortusingjava8(names2); system.out.println(names2); } //sort using java 7 private void sortusingjava7(list<string> names) { collections.sort(names, new comparator<string>() { @override public int compare(string s1, string s2) { return s1.compareto(s2); } }); } //sort using java 8 private void sortusingjava8(list<string> names) { collections.sort(names, (s1, s2) -> s1.compareto(s2)); } }
run the program to get the following result.
sort using java 7 syntax: [ kalpesh mahesh naresh ramesh suresh ] sort using java 8 syntax: [ kalpesh mahesh naresh ramesh suresh ]
here the sortusingjava8() method uses sort function with a lambda expression as parameter to get the sorting criteria.