[61e40d]: / util / CollectionsEx.java

Download this file

96 lines (83 with data), 2.7 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Provides additional methods for collection operation
* @author zhengc
*
*/
public class CollectionsEx {
@SuppressWarnings("hiding")
/**
* Returns sorted HashMap by descend Value
* @param map the original HashMap
* @return sorted HashMap by descend Value
*/
public static <String, Double extends Comparable<? super Double>> Map<String, Double> sortByValueR( Map<String, Double> map ) {
/* sort map by value reversed*/
List<Map.Entry<String, Double>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, Collections.reverseOrder(new Comparator<Map.Entry<String, Double>>() {
public int compare( Map.Entry<String, Double> o1, Map.Entry<String, Double> o2 ) {
return ( o1.getValue() ).compareTo( o2.getValue() );
}
}) );
Map<String, Double> result = new LinkedHashMap<>();
for (Map.Entry<String, Double> entry : list){
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
@SuppressWarnings("hiding")
/**
* Returns sorted HashMap by Value
* @param map the original HashMap
* @return sorted HashMap by Value
*/
public static <String, Double extends Comparable<? super Double>> Map<String, Double> sortByValue( Map<String, Double> map ) {
/* sort map by value*/
List<Map.Entry<String, Double>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
public int compare( Map.Entry<String, Double> o1, Map.Entry<String, Double> o2 ) {
return ( o1.getValue() ).compareTo( o2.getValue() );
}
} );
Map<String, Double> result = new LinkedHashMap<>();
for (Map.Entry<String, Double> entry : list){
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
// public static Map<String, String> sortByKey(Map<String, String> map ) {
// /* sort map by key*/
// Map<String, String> sortedmap = new HashMap<String, String>();
// Set<String> keys = map.keySet();
// List<String> key_list = setToList(keys);
// Collections.sort(key_list);
//
// for(String key : key_list) {
// System.out.println(key);
// sortedmap.put(key, map.get(key));
// }
// return sortedmap;
// }
/**
* Creates a list from a set
* @param set a set
* @return a list
*/
public static List<String> setToList(Set<String> set) {
List<String> list = new ArrayList<String>();
for (String s: set) {
list.add(s);
}
Collections.sort(list);
return list;
}
}