Java 8 for beginners - Part 1

Java 8 for beginners - Part 1

Dec 01, 2021

1.Java 8 for beginners - Part 1 (https://www.buymeacoffee.com/sn04/java-8-beginners-part-1)

Introduction

JAVA 8 is a major feature release of Java programming language. It was initially released on 18 March 2014. Java 8 provides support for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc.

Below are some of the new features in Java 8 :

1) Lambda expression − Adds functional processing capability to Java.

2) Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.

3) Default method − Interface to have default method implementation.

4) New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.

5) Stream API − New stream API to facilitate pipeline processing.

6) Date Time API − Improved date time API.

7) Optional − Emphasis on best practices to handle null values properly.

8) Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.

Check out below program to sort names in Java 7 vs Java 8 to understand how lambda help us write a clean and elegant code in java.

import java.util.ArrayList;
import java.util.Collections;

import java.util.Comparator;

import java.util.List;


public class Main {

public static void main(String[] args) {

List<String> names1 = new ArrayList<String>();

names1.add("Sam ");

names1.add("James ");

names1.add("Wilson ");

names1.add("Edward ");

names1.add("Ramesh ");

List<String> names2 = new ArrayList<String>();

names2.add("Sam ");

names2.add("James ");

names2.add("Wilson ");

names2.add("Edward ");

names2.add("Ramesh ");

Main tester = new Main();

System.out.println("Sort using Java 7 syntax: ");

tester.sortByJava7(names1);

System.out.println(names1);

System.out.println("Sort using Java 8 syntax: ");

tester.sortByJava8(names2);

System.out.println(names2);

}

//sort by java 7

private void sortByJava7(List<String> names) {

Collections.sort(names, new Comparator<String>() {

@Override

public int compare(String s1, String s2) {

return s1.compareTo(s2);

}

});

}

//sort by java 8

private void sortByJava8(List<String> names) {

Collections.sort(names, (s1, s2) -> s1.compareTo(s2));

}

}

Output :

Sort using Java 7 syntax:

[Edward , James , Ramesh , Sam , Wilson ]

Sort using Java 8 syntax:

[Edward , James , Ramesh , Sam , Wilson ]

Thank you folks. If you like my article, you can support me by buying me a coffee.

Enjoy this post?

Buy Shanker a coffee

More from Shanker