排序实现正序,逆序和限定取数数量(前几位)
/**
* @author ZengL
* @description
* @since 2024/7/29
*/
public class ComCollectionUtil {
/**
* map排序取限定数量
*
* @param map 排序map
* @param asc 是否升序
* @param limit 限定数量
* @param <K> 键
* @param <V> 值
* @return 数据(排序取值后的新map)
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortMap(Map<K, V> map, boolean asc, Integer limit) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> {
int compare = (o1.getValue()).compareTo(o2.getValue());
if (asc) {
return compare;
} else {
return -compare;
}
});
if (ObjectUtil.isNotNull(limit)) {
list = list.subList(0, limit);
}
Map<K, V> returnMap = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
public static void main(String[] args) {
Map<String, Long> stringLongMap = new HashMap<>(15);
stringLongMap.put("111", 111L);
stringLongMap.put("222", 222L);
stringLongMap.put("333", 333L);
stringLongMap.put("444", 444L);
stringLongMap.put("555", 555L);
stringLongMap.put("666", 666L);
stringLongMap.put("777", 777L);
stringLongMap.put("888", 888L);
stringLongMap.put("999", 999L);
Map<String, Long> stringIntegerMap = sortMap(stringLongMap, true, 5);
Map<String, Long> stringIntegerMap1 = sortMap(stringLongMap, false, 5);
System.out.println(new ArrayList<>(stringIntegerMap.entrySet()));
System.out.println(new ArrayList<>(stringIntegerMap1.entrySet()));
}
}
输出
[111=111, 222=222, 333=333, 444=444, 555=555]
[999=999, 888=888, 777=777, 666=666, 555=555]