使用lambda给list对象排序示例
效果:
代码:
package com.alexli.test;
import com.alexli.codetemplate.util.DateUtil;
import com.alexli.entity.Message;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Message> msgList = new ArrayList<>();
msgList.add(new Message(1, "A", DateUtil.fmtStrToDate("2019-03-16 18:05:10")));
msgList.add(new Message(4, "D", DateUtil.fmtStrToDate("2019-03-16 18:05:40")));
msgList.add(new Message(3, "C", DateUtil.fmtStrToDate("2019-03-16 18:05:30")));
msgList.add(new Message(2, "B", DateUtil.fmtStrToDate("2019-03-16 18:05:20")));
//发送时间正序排序
msgList.sort((Message m1, Message m2) -> m1.getSendDate().compareTo(m2.getSendDate()));
System.out.println("按消息发送时间正序排序:");
for (Message message : msgList) {
System.out.println(message.toString());
}
//消息ID倒序排序
msgList.sort((Message m1, Message m2) -> m1.getId().compareTo(m2.getId()));
System.out.println("\n按消息ID倒序排序:");
for (Message message : msgList) {
System.out.println(message.toString());
}
//消息内容字典倒序排序
msgList.sort((Message m1, Message m2) -> m2.getMsg().compareTo(m1.getMsg()));
System.out.println("\n按消息内容字典倒序排序:");
for (Message message : msgList) {
System.out.println(message.toString());
}
}
}