Java 8 has included a lot of new features, this post will explain a few important features.
- Lamda Expressions.
- Functional Interfaces.
- Streams
- Nashorn
Other features.
- Date and time api changes.
- Foreach.
——————————————
Lamda expressions
——————————————
Lamda expression is a function with no name and with implementation.
A basic expression format would be..
(x, y) -> x + y
Where (x, y) are the function input parameters. And x+y is the statement executed by the function and returned.
Example:
FileFilter filterLamda = (File pathName) -> pathName.getName().endsWith(".png");
File dir = new File("/Users/deiveehannallazhagappan/workspace/xplore-java/supporting");
File[] files = dir.listFiles(filterLamda);
for (File f: files) {
System.out.println("f = " + f);
}
——————————————
Functional Interfaces
——————————————
Functional interfaces are interfaces that have only one abstract method in it.
Example:
@FunctionalInterface
public interface TestFuncInterface {
public void testmethod();
default void testdefaultmethod(){
System.out.println(“default method“);
}
}
Lamda expressions can be used to represent the instance of a functional interface.
Note:
- You can add default methods .
——————————————
Streams
——————————————
Streams are new feature introduced in Java 8 to simplify the logic required to process data - filtering, transforming data etc.,
For example, the below example does the following
- Creates a new array list from 1-30
- Creates a stream of integers.
- Filters the list by extracting only no.s divisible by 3 and converts them into a integer array.
Stream example:
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i< 30; i++){
list.add(i);
}
Stream<Integer> stream = list.stream();
Integer[] evenNumbersArr = stream.filter(i -> i%3 == 0).toArray(Integer[]::new);
System.out.print(evenNumbersArr);
Why streams: reduce complexity, less code.
——————————————
Nashorn
——————————————
Nashorn is a javascript engine which allows the java applications to interact with the JS code.
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("nashorn");
engine.eval("print('deiveehan')");
You can also execute an external script instead of using inline js code.
engine.eval(new FileReader("/Users/deiveehannallazhagappan/workspace/xplore-java/supporting/js/deiveescript.js"));
You will get the output of the js code when you run the java application.
No comments:
Post a Comment