|
| 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.HashMap; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.Map.Entry; |
| 10 | +import java.util.TreeMap; |
| 11 | + |
| 12 | +import com.javatechie.stream.api.example.Employee; |
| 13 | + |
| 14 | +public class SortMapDemo { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + |
| 18 | + Map<String, Integer> map = new HashMap<>(); |
| 19 | + map.put("eight", 8); |
| 20 | + map.put("four", 4); |
| 21 | + map.put("ten", 10); |
| 22 | + map.put("two", 2); |
| 23 | + |
| 24 | + Map<Employee, Integer> employeeMap = new TreeMap<>((o1, o2) -> (int) (o2.getSalary() - o1.getSalary())); |
| 25 | + employeeMap.put(new Employee(176, "Roshan", "IT", 600000), 60); |
| 26 | + employeeMap.put(new Employee(388, "Bikash", "CIVIL", 900000), 90); |
| 27 | + employeeMap.put(new Employee(470, "Bimal", "DEFENCE", 500000), 50); |
| 28 | + employeeMap.put(new Employee(624, "Sourav", "CORE", 400000), 40); |
| 29 | + employeeMap.put(new Employee(284, "Prakash", "SOCIAL", 1200000), 120); |
| 30 | + |
| 31 | + System.out.println(employeeMap); |
| 32 | + |
| 33 | + List<Entry<String, Integer>> entries = new ArrayList<>(map.entrySet()); |
| 34 | + Collections.sort(entries, (o1, o2) -> o1.getKey().compareTo(o2.getKey())); |
| 35 | + |
| 36 | + /* |
| 37 | + * for (Entry<String, Integer> entry : entries) { |
| 38 | + * System.out.println(entry.getKey() + " " + entry.getValue()); } |
| 39 | + */ |
| 40 | + |
| 41 | + // map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println); |
| 42 | + System.out.println("****************************"); |
| 43 | + // map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println); |
| 44 | + |
| 45 | + employeeMap.entrySet().stream() |
| 46 | + .sorted(Map.Entry.comparingByKey(Comparator.comparing(Employee::getDept).reversed())) |
| 47 | + .forEach(System.out::println); |
| 48 | + |
| 49 | + } |
| 50 | +} |
0 commit comments