使用Lambda表达式对HashMap按value对象的时间属性进行降序排序
HashMap<Integer, User> userMap = new HashMap<>();
userMap.put(1,new User("张三",8,new Date().getTime()));
userMap.put(2,new User("李四",10,new Date().getTime()));
userMap.put(3,new User("王五",20,new Date().getTime()));
userMap.put(4,new User("赵六",15,new Date().getTime()));
List<Map.Entry<Integer, User>> list = new ArrayList<>(userMap.entrySet());
Collections.sort(
(a.getValue().getTime() !=null ? a.getValue().getTime().getTime() : 0) >
(b.getValue().getTime() !=null ? b.getValue().getTime().getTime() : 0) ? -1:1 );
//list转map
userMap=list.stream()
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (oldValue,newValue) -> newValue, LinkedHashMap::new));
排序后list是排序后的结果,但如果还想返回排序后的userMap,则需要把list转化成Map,才能使排序生效
@Data
public class User{
private String name;
private int age;
private Date time;
public User(String name,int age,Date time){
this.name = name;
this.age = age;
this.time = time;
}
}