Skip to content

Commit a1d2337

Browse files
authored
sort a list using lambda in java 8
1 parent 0a5ebe5 commit a1d2337

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

sort/SortListDemo.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.javatechie.stream.sort;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.Comparator;
6+
import java.util.List;
7+
8+
import com.javatechie.stream.api.example.DataBase;
9+
import com.javatechie.stream.api.example.Employee;
10+
11+
public class SortListDemo {
12+
13+
public static void main(String[] args) {
14+
15+
List<Integer> list = new ArrayList<>();
16+
list.add(8);
17+
list.add(3);
18+
list.add(12);
19+
list.add(4);
20+
21+
List<Employee> employees = DataBase.getEmployees();
22+
23+
/*Collections.sort(employees, new Comparator<Employee>() {
24+
25+
@Override
26+
public int compare(Employee o1, Employee o2) {
27+
return (int) (o1.getSalary() - o2.getSalary());// ascending
28+
}
29+
});*/
30+
31+
32+
Collections.sort(employees, ( o1, o2) ->(int) (o1.getSalary() - o2.getSalary()));
33+
34+
//System.out.println(employees);
35+
36+
37+
//employees.stream().sorted(( o1, o2) ->(int) (o2.getSalary() - o1.getSalary())).forEach(System.out::println);
38+
39+
//employees.stream().sorted(Comparator.comparing(emp->emp.getSalary())).forEach(System.out::println);
40+
41+
employees.stream().sorted(Comparator.comparing(Employee::getDept)).forEach(System.out::println);
42+
43+
/*
44+
* Collections.sort(list);//ASSENDING Collections.reverse(list);
45+
* System.out.println(list);
46+
*
47+
* list.stream().sorted(Comparator.reverseOrder()).forEach(s->System.out.println
48+
* (s));//descending
49+
*/
50+
51+
}
52+
}

0 commit comments

Comments
 (0)