In this tutorial, We'll learn how to write programs using java 8 lambda and Stream concepts with examples. Many developers feel learning java 8 concepts may be hard to understand. But once we are good using them then feel reduces error prone code and improves the performance of the application.
Read article on Java 8 Lamda Expression Rules
In this article, We will see the example programs on sorting using Comparator, File names validation, Retrieving only hidden files and filtering list objects based on conditions.
See the below code which is implemented in older versions of Java. Here trying to sort the Employee's based on the id column.
Collections.sort(emplyeesList, new Comparator() { public int compare(Employee a1, Employee a2){ return a1.getId().compareTo(a2.getId()); } });
Here, written code in 5 lines in which includes Comparator implementation.
emplyeesList.sort(Comparator.comparing(Employee::getId));
Here, Comparator is a Functional Interface which has only one abstract method.
Comparator has a static method comparing(.Function.) which accepts only Funtion interface.
https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html
Note: Function<T, R> also a Functional Interface. This has a method apply(T t) which will be called from Comparator.comparing() method.
See the code in java old version. Here the core logic is file.getName().endsWith(".xml"); The remaining code is just syntax.
File[] hiddenFiles = new File("directory_name").listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().endsWith(".xml"); } });
File[] hiddenFiles = new File("directory_name").listFiles( file -> file.getName().endsWith(".xml"));
Note: Java 8, just focus on the business logic and takes its syntax internally. Developer need not to worry about it.
File has a method to check the method is hidden or not using isHidden() method.
File[] hiddenFiles = new File("directory_name").listFiles(new FileFilter() { public boolean accept(File file) { return file.isHidden(); } });
File[] hiddenFiles = new File("directory_name").listFiles(File::isHidden);
In this post, We've seen example lambda program before and after Java 8.
Observed the differences between them. Java 8 were in many ways more profound than any other changes to Java in its history.
No comments:
Post a Comment
Please do not add any spam links in the comments section.