Skip to content

Commit d1d97d1

Browse files
committed
Added sort() using Comparator in Stream Operation
1 parent 41b1dbe commit d1d97d1

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ This repository contains the basic &amp; 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

0 commit comments

Comments
 (0)