Java 8
Method Reference
To shorten the syntax with the help of for Each
List names = new ArrayList();
names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");
names.forEach(System.out::println);
Default Methods
To declare the function in the interface, so that we can apply the function directly without implementation of interface
interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
}
vehicle.print() // I am a vehicle
Stream
To take array List or Collection as a input and output as another format
Filter: Filter out the input when the data is false
Limit: set the number of output size
map: change into other format
List<Student> studentList = studentRepository.findAll();
List<StudentData> studentDataList =
studentList.stream()
.filter(student -> !containChinese(student.getStudentName()))
.limit(1)
.map(StudentConvertor::convertFromModalToData)
.collect(Collectors.toList());
Optional
Allow value of null and do null handling to prevent from NullPointer Exception
Integer sum(Optional<Integer> a, Optional<Integer> b) {
Integer value1 = a.orElse(2);
Integer value2 = b.orElse(1);
return value1 + value2;
}
Optional<Integer> a = Optional.ofNullable(null);
Optional<Integer> b = Optional.ofNullable(3);
System.out.println(sum(a, b)); // 5
Local Date
It is used to replace traditional java.util.Date
Here is the example convert string into local date time format
String dateStr = "2020-5-18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd");
LocalDate date = LocalDate.parse(dateStr,formatter);
Reference
Last updated
Was this helpful?