File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Modern-Java-Examples/src/com/learn/defaults Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change @@ -62,6 +62,8 @@ This repository contains the basic & 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
You can’t perform that action at this time.
0 commit comments