map 按 key 升序排序
private Map<String, Object> sortByKey(Map<String, Object> map) {
Map<String, Object> result = new LinkedHashMap<>(map.size());
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
map根据属性排序、取出map前n个、后n个
public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(Map<K, V> map, int flag) {
LinkedHashMap<K, V> sortMap = new LinkedHashMap<>();
if (flag == 1) {
map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
} else {
map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
}
return sortMap;
}
public LinkedHashMap<String, Double> subMap(LinkedHashMap<String, Double> map, int length) {
List<Map.Entry<String, Double>> lists = new ArrayList<>(map.entrySet());
LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<>();
if (lists.size() >= length) {
for (Map.Entry<String, Double> set : lists.subList(0, length)) {
sortedMap.put(set.getKey(), set.getValue());
}
} else {
for (Map.Entry<String, Double> set : lists) {
sortedMap.put(set.getKey(), set.getValue());
}
}
return sortedMap;
}
protected LinkedHashMap<Date, BigDecimal> subMap(LinkedHashMap<Date, BigDecimal> map, int length) {
List<Map.Entry<Date, BigDecimal>> lists = new ArrayList<>(map.entrySet());
LinkedHashMap<Date, BigDecimal> sortedMap = new LinkedHashMap<>();
int size = lists.size();
if (size >= length) {
for (Map.Entry<Date, BigDecimal> set : lists.subList(size -length, size)) {
sortedMap.put(set.getKey(), set.getValue());
}
} else {
for (Map.Entry<Date, BigDecimal> set : lists) {
sortedMap.put(set.getKey(), set.getValue());
}
}
return sortedMap;
}