一、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/n/137344.html
微信扫一扫
支付宝扫一扫