Monday, May 25, 2020

Lambda Expressions & Streams - Data Manipulation- Learning-1

Lambda Expressions are new feature addition in Java 8 which is mainly to send methods/Functions as an object to process. Based on the object, the implementation of the interface will vary. Java now tries to play a functional programming role. Now functions are defined based on the object behavior.

Data Manipulation

Data Collection, Data manipulation are the most important activities in the information world. Lambda expressions and streams help in the Data manipulation. Data manipulation is the area which filters some particular data based on a few criterias. In SQL we have DDL (data definition Language) and DML (Data manipulation Language) in each database. In Java, all data is collected in the form of Arrays, Collections, Maps. Data Manipulation happens by iterating each object and applying the functionality.


for(Object o : object[]){
// perform some operation on ‘o’
}

These operations are the one specified in lambda expression.
To print list of file names in a Directory

File[] files = new File(“.”).listFiles()


Without Streams


for(File file : files){
System.out.println(file.getCanonicalPath());
}


With Streams

Stream<File> fileStream = Stream.of(files);
fileStream.forEach(x-> {
try {
System.out.println(x.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
});


Here x is the single object reference to file, on the x object the print function is applied. The iteration code is taken care of by Streams. Iteration is a boilerplate code. Now the question arises 

  • what is the big deal? 
  • why not iteration taken care by developers? 
  • why do you keep that in JVM.
To answer the above questions, in a real development scenario, the filters to be applied are very huge on the huge dataset. Iterating over the data collection is also single-threaded. Some framework is built using Streams to perform better data manipulation.

No comments:

Post a Comment

Reading and Writing JSON to a file

Why GSON? Nowadays JSON is more frequently used for data representation. There are a lot of libraries to convert java objects into JSO...