Skip to content

Commit b546e2a

Browse files
committed
default method in interfaces
1 parent 70000fd commit b546e2a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.learn.defaults;
2+
3+
import com.learn.data.Student;
4+
import com.learn.data.StudentDataBase;
5+
6+
import java.util.Collections;
7+
import java.util.Comparator;
8+
import java.util.List;
9+
import java.util.stream.Collectors;
10+
11+
public class DefaultsMethodExample {
12+
13+
public static void main(String[] args) {
14+
15+
/**
16+
* Sort the list of names in alphabetical order.
17+
*/
18+
List<String> stringList = StudentDataBase.getAllStudents().stream().map(Student::getName).collect(Collectors.toList());
19+
20+
/**
21+
* Prior Java8, by using Collections class.
22+
*/
23+
Collections.sort(stringList); // sort the input in alphabetical order
24+
System.out.println("Sorted list using Collections.sort() : " + stringList);
25+
26+
/**
27+
* Java8 approach,
28+
* In Java8, the List interface has a default method sort
29+
* And this sort method, takes an input called Comparator.
30+
* By this default methods, it helps to add new functionalities into the interfaces so that this interface
31+
* can evolve according to the new technology and new use cases.
32+
*/
33+
List<String> stringList1 = StudentDataBase.getAllStudents().stream().map(Student::getName).collect(Collectors.toList());
34+
stringList1.sort(Comparator.naturalOrder());
35+
System.out.println("Sorted list using List.sort() : " + stringList1);
36+
}
37+
}

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ This repository contains the basic &amp; advance level examples related to Java
6262
* [orElse(), orElseGet() and orElseThrow()](Modern-Java-Examples/src/com/learn/optional/OptionalOrElseExample.java)
6363
* [ifPresent() and isPresent()](Modern-Java-Examples/src/com/learn/optional/OptionalPresentExample.java)
6464
* [filter(), map() and flatMap()](Modern-Java-Examples/src/com/learn/optional/OptionalMapFlatMapExample.java)
65+
* **Defaults**
66+
* [default methods](Modern-Java-Examples/src/com/learn/defaults/DefaultsMethodExample.java)
6567

6668
<hr />
6769

0 commit comments

Comments
 (0)