Skip to content

Commit 23fc41d

Browse files
committed
ArrayList and TreeSet
1 parent e57bd76 commit 23fc41d

1 file changed

Lines changed: 40 additions & 6 deletions

File tree

‎core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
import com.baeldung.performance.Employee;
44

5-
import java.util.HashMap;
6-
import java.util.Map;
7-
import java.util.TreeMap;
5+
import java.util.*;
86

97
public class SortHashMap {
108

@@ -14,11 +12,28 @@ public static void main(String[] args) {
1412

1513
initialize();
1614

17-
treeMapSortByKey();
15+
//treeMapSortByKey();
16+
17+
//arrayListSortByValue();
18+
//arrayListSortByKey();
19+
20+
treeSetByKey();
21+
treeSetByValue();
22+
}
23+
24+
private static void treeSetByValue() {
25+
Comparator<Employee> comp = (Employee o1, Employee o2) -> (o1.getId().compareTo(o2.getId()));
26+
SortedSet<Employee> values = new TreeSet<>(comp);
27+
values.addAll(map.values());
28+
System.out.println(values);
1829
}
1930

20-
public static void treeMapSortByKey()
21-
{
31+
private static void treeSetByKey() {
32+
SortedSet<String> keys = new TreeSet<>(map.keySet());
33+
System.out.println(keys);
34+
}
35+
36+
private static void treeMapSortByKey() {
2237
TreeMap<String, Employee> sorted = new TreeMap<>(map);
2338
sorted.putAll(map);
2439

@@ -29,6 +44,25 @@ public static void treeMapSortByKey()
2944

3045
}
3146

47+
private static void arrayListSortByValue() {
48+
List<Employee> employeeById = new ArrayList<>(map.values());
49+
50+
Collections.sort(employeeById, new Comparator<Employee>() {
51+
52+
public int compare(Employee o1, Employee o2) {
53+
return (int)(o1.getId() - o2.getId());
54+
}
55+
});
56+
57+
System.out.println(employeeById);
58+
}
59+
60+
private static void arrayListSortByKey() {
61+
List<String> employeeByKey = new ArrayList<>(map.keySet());
62+
Collections.sort(employeeByKey);
63+
System.out.println(employeeByKey);
64+
}
65+
3266
private static void initialize() {
3367
Employee employee1 = new Employee(1L, "Mher");
3468
map.put(employee1.getName(), employee1);

0 commit comments

Comments
 (0)