一、Map根據key排序
Map是一種鍵值對映射的數據結構,其中的元素是以鍵值對的形式存儲,但是Map中的元素並不是有序的,如果需要根據鍵值進行排序,可以使用TreeMap。TreeMap是通過紅黑樹實現的,自然排序時會按照鍵值升序排列。
Map<String, Object> map = new TreeMap<>();
map.put("b", 2);
map.put("a", 1);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}
二、Map按key值排序
除了使用TreeMap進行排序外,還可以使用Stream API來對Map進行排序。可以先將Map轉換成Set,然後根據key值進行排序,最後將排序後的元素再存入LinkedHashMap中。LinkedHashMap是一種基於哈希表和雙向鏈表實現的Map,所以可以保持元素的插入順序。
Map<String, Object> map = new HashMap<>();
map.put("b", 2);
map.put("a", 1);
map.put("c", 3);
Map<String, Object> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new));
System.out.println(sortedMap); // {a=1, b=2, c=3}
三、@MapKey
@MapKey註解可以用在方法上,表示返回的Map中以哪個屬性作為key。通常用於處理一對多關係。下面是一個例子,一個班級可以有多個學生,一個學生只能屬於一個班級。
class Student {
private String name;
@MapKey("className")
private Map<String, ClassRoom> classRooms;
// getter and setter
}
class ClassRoom {
private String className;
// getter and setter
}
// 初始化數據
List<ClassRoom> classRooms = Arrays.asList(new ClassRoom("math"), new ClassRoom("english"));
Map<String, List<Student>> map = new HashMap<>();
map.put("classA", Arrays.asList(new Student("Tom", classRooms.get(0)),
new Student("Mary", classRooms.get(0))));
// 使用@MapKey
Map<String, List<ClassRoom>> result = map.values().stream()
.flatMap(Collection::stream)
.flatMap(s -> s.getClassRooms().values().stream())
.distinct()
.collect(Collectors.toMap(ClassRoom::getClassName,
c -> map.values().stream()
.flatMap(Collection::stream)
.filter(s -> s.getClassRooms().containsValue(c))
.collect(Collectors.toList())));
System.out.println(result); // {math=[Tom, Mary], english=[]}
四、@MapKey is required
@MapKey註解還有一個可選的屬性is required,默認值為false。如果設為true,表示返回的Map中,@MapKey註解所標註的屬性值是必須存在的,如果不存在則會拋出異常。
class User {
private String name;
private String id;
private Map<String, String> attr;
// getter and setter
}
// 初始化數據
User user = new User();
user.setName("Tom");
user.setId("111");
// 沒有使用@MapKey(required = true)
Map<String, Object> map = new HashMap<>();
map.put("name", user.getName());
map.put("id", user.getId());
user.getAttr().forEach(map::put);
System.out.println(map); // {name=Tom, id=111, attr1=value1, attr2=value2}
// 使用@MapKey(required = true),其中attr是空則會拋出異常
map = new HashMap<>();
map.put("name", user.getName());
map.put("id", user.getId());
Optional.ofNullable(user.getAttr())
.orElseThrow(() -> new IllegalArgumentException("attr is required"))
.forEach((k, v) -> map.put(k, v));
System.out.println(map); // {name=Tom, id=111, attr1=value1, attr2=value2}
原創文章,作者:WQIN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/137344.html
微信掃一掃
支付寶掃一掃