# Java 8

## Method Reference

* To shorten the syntax with the help of for Each

```java
 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

```java
interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
}

vehicle.print() // I am a vehicle
```

## Stream&#x20;

* 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

```java
List<Student> studentList = studentRepository.findAll();
List<StudentData> studentDataList = 
    studentList.stream()
    .filter(student -> !containChinese(student.getStudentName()))
    .limit(1)
    .map(StudentConvertor::convertFromModalToData)
    .collect(Collectors.toList());
```

## &#x20;Optional

* Allow value of null and do null handling to prevent from NullPointer Exception

```java
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&#x20;

* It is used to replace traditional java.util.Date
* Here is the example convert string into local date time format

```java
String dateStr = "2020-5-18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd");
LocalDate date = LocalDate.parse(dateStr,formatter);
```

## Reference

{% embed url="https://www.tutorialspoint.com/java8/java8_optional_class.htm" %}
