Java 8 is considered to be a major milestone for Java. With a history of being one of the foremost languages of choice for mainstream commercial world, Java was supposed to evolve by leaps and bounds in today’s age of distributed computing, parallel processing and cloud strategy. Java 8 emerges as an evolved java version with many features of functional languages like Scala without losing its clarity, simplicity and OOP paradigm. Let us have a look at the major advancements in Java 8:
1. Lambda Expressions
Project Lambda is probably the most prominent feature of Java 8. Lambda expressions are designed to allow code to be streamlined. When a Lambda expression is written, it is translated into a functional interface at compile time. Few examples of lambda expression are as follows:
1.1 Listener Lambda
Lambda expression can be used to specify action listeners while working with Java Swing.
1 2 3 4 5 6 7 8 9 10 11 12 | JButtonfirstButton=newJButton("First Button"); //Old way of specifying listener firstButton.addActionListener(newActionListener(){ @Override publicvoidactionPerformed(ActionEventae){ System.out.println("I am old listener."); } }); //New way of specifying listener firstButton.addActionListener(e -> System.out.println("I am new listener.")); |
1.2 Runnable Lambda
Lambda Expressions can be used with Runnable interface as well.
1 2 3 4 5 6 7 8 9 10 | // Old anonymous Runnable Runnable r1 =newRunnable(){ @Override publicvoidrun(){ System.out.println("This is anonymous runnable example."); } }; // New Lambda Runnable Runnable r2 =()->System.out.println("This is lambda runnable example."); |
2. java.util.stream Package
The Stream interface is located in the java.util.stream package. It represents a sequence of objects somewhat like the Iterator interface. However, unlike the Iterator, there are two "modes" for a stream: sequential and parallel. It uses fork/join parallelism to split up the work and speed the processing along. Streams have the ability to filter, map, and reduce while being traversed. There are also corresponding primitive streams - IntStream, DoubleStream, and LongStream. Let us see an example.
We can get the sum of the weight of red colored widgets from Collection<Widget> widgets as:
1 2 3 4 | int sum = widgets.stream() .filter(b ->b.getColor() == RED) .mapToInt(b ->b.getWeight()) .sum(); |
3. Default Methods
Default methods are also known as Defender Methods or Virtual Extension methods. These can be added to any interface; i.e. an interface can have default method with implementation. As the name suggests, any class which implements this interface and does not provide any implementation to such methods, will get the default implementation. Let us have a look at Iterable interface in Java 8:
1 2 3 4 5 6 7 8 9 10 | @FunctionalInterface publicinterfaceIterable{ Iteratoriterator(); defaultvoidforEach(Consumer<?superT>action){ Objects.requireNonNull(action); for(Tt:this){ action.accept(t); } } } |
4. Nashorn
Nashorn replaces Rhino as the default JavaScript engine for the Oracle JVM. It comes with a command line tool jjs. It is very much like V8 engine provided by chrome which runs Node.js. Nashorn uses invokedynamic property of the JVM.
In order to run a javascript file using jjs, we need to execute:
1 | $ jjs someScript.js
|
To use ScriptEngine in java code, we need to make following imports:
1 2 | import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; |
Then we need to get nashorn from ScriptEngineManager.
1 2 | ScriptEngineManager engineManager = newScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); |
Now javascript can be executed from anywhere in the code as:
1 2 | engine.eval("function raiseAlert(message) { alert(message) }"); engine.eval("raiseAlert('This is my first Nashorn Program.’);"); |
5. Java Date and Time API
Till Java 8, java had a very cumbersome date and time API. Java 8 introduces a new Date/Time API which is thread -safe, easier to read and more comprehensive than the previous API. New classes have been created to get the dates:
LocalDate - Day, Month, Year.
LocalTime - Time of day only.
LocalDateTime - Both Date and Time.
This makes the addition and comparison of dates much simpler and easy.
1 2 | LocalTimenow=LocalTime.now(); LocalTimelater=now.plus(12,HOURS); |
There are also well-named methods such as plusDays, plusMonths, minusDays and minusMonths.
6. No more Permanent Generation
Now allocations for the class metadata are done from the native memory. This implies:
a. We do not need to set XX:PermSize options anymore.
b. Out of memory error has got modified. Previously it was java.lang.OutOfMemoryError: Permgen space. It has now been modified to java.lang.OutOfMemoryError: Metadata space.
This is not an exhaustive list of Java 8 features. There are various remarkable improvements. There is a lot to explore. Time to switch to Java 8.
0 comments:
Post a Comment