File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
Modern-Java-Examples/src/com/learn/streams Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .learn .streams ;
2+
3+ import com .learn .data .Student ;
4+ import com .learn .data .StudentDataBase ;
5+
6+ import java .util .Comparator ;
7+ import java .util .List ;
8+ import java .util .stream .Collectors ;
9+
10+ public class StreamsComparatorExample {
11+
12+ public static void main (String [] args ) {
13+
14+ sortStudentsByName ().forEach (System .out ::println );
15+
16+ sortStudentsByGpa ().forEach (System .out ::println );
17+
18+ }
19+
20+ /**
21+ * <p>
22+ * Students need to be sorted by their name
23+ * </p>
24+ */
25+ public static List <Student > sortStudentsByName () {
26+ System .out .println ("Sorted by Name:" );
27+ return StudentDataBase .getAllStudents ().stream ()
28+ .sorted (Comparator .comparing (Student ::getName ))
29+ .collect (Collectors .toList ());
30+ }
31+
32+ /**
33+ * <p>
34+ * Sort the Students by their GPA in Decreasing Order.
35+ * used reversed() to reverse the result and return the Collection.
36+ * </p>
37+ * @return
38+ */
39+ public static List <Student > sortStudentsByGpa () {
40+ System .out .println ("Sorted By Gpa: " );
41+ return StudentDataBase .getAllStudents ().stream ()
42+ .sorted (Comparator .comparing (Student ::getGpa ).reversed ())
43+ .collect (Collectors .toList ());
44+ }
45+ }
Original file line number Diff line number Diff line change @@ -28,6 +28,7 @@ This repository contains the basic & advance level examples related to Java
2828 * [ map()] ( Modern-Java-Examples/src/com/learn/streams/StreamsMapExample.java )
2929 * [ flatMap()] ( Modern-Java-Examples/src/com/learn/streams/StreamsFlatMapExample.java )
3030 * [ distinct(), count() and sorted()] ( Modern-Java-Examples/src/com/learn/streams/StreamsFlatMapExample.java )
31+ * [ sort() using Comparator] ( Modern-Java-Examples/src/com/learn/streams/StreamsComparatorExample.java )
3132
3233
3334
You can’t perform that action at this time.
0 commit comments