通过Collections实现排序
来源:互联网 发布:cs1.6 for mac 10.11 编辑:程序博客网 时间:2024/04/29 08:08
要进行排序的实体类,该实体类按照birthDay属性进行排序。
注意birthDay为String类型。
public class User2 {private String username;private String birthDate;public User2() {}public User2(String username, String birthDate) {super();this.username = username;this.birthDate = birthDate;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getBirthDate() {return birthDate;}public void setBirthDate(String birthDate) {this.birthDate = birthDate;}}
实现一个Comparator接口。
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Comparator;import java.util.Date;public class User2Comparator implements Comparator<User2> {public int compare(User2 o1, User2 o2) {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date o1Date = new Date();Date o2Date = new Date();try {o1Date = df.parse(o1.getBirthDate());o2Date = df.parse(o2.getBirthDate());} catch (ParseException e) {e.printStackTrace();}return o1Date.compareTo(o2Date);}}
测试效果。
import java.util.ArrayList;import java.util.Collections;import java.util.List;import org.junit.Test;import com.boco.myeat.model.User2;import com.boco.myeat.model.User2Comparator;public class DateTest {@Testpublic void testDate(){List<User2> users = new ArrayList<User2>();User2 u1 = new User2("zhang", "1986-01-11 12:10:10");User2 u2 = new User2("wang", "1987-01-02 15:20:34");User2 u3 = new User2("li", "1984-01-02 15:20:34");users.add(u1);users.add(u2);users.add(u3);for(User2 u : users){System.out.println(u.getUsername());}System.out.println("=============");Collections.sort(users, new User2Comparator());Collections.reverse(users);for(User2 u : users){System.out.println(u.getUsername());}}}
- 通过Collections实现排序
- 通过Collections.sort 给 List 排序
- java List 通过Collections.sort排序
- List实现Collections帮助类的排序
- 实现用Collections.sort(arg1,arg2)排序
- 用Collections.sort()实现按照首字母排序
- [java]_[Collections.sort()实现List排序]
- 应用 Collections.sort() 实现 List 排序
- Collections.sort()实现对List的排序
- Java实现距离排序【Collections.sort】
- Collections(排序)
- Java排序 Collections排序
- Collections.sort(list)排序需要实现comparable借口
- Collections结合Comparator实现对列表的快速排序
- 使用Collections.sort()实现List正反排序的方法
- Collections.sort中使用Comparator的实现类排序
- List自定义排序根据Collections.sort重载方法来实现
- 通过qsort实现快速排序
- poj 1850 Code
- 数据库并发处理方法
- Java的内存复制(主要是数组)效率比较
- IO视频学习——FileWriter,FileReader简单操作
- poj 2065 SETI
- 通过Collections实现排序
- Silverlight实战示例2(兼集合属性的妙用)--实体的组织
- poj2417 Discrete Logging
- SQL2005中设置自动编号字段
- Java IO _Scanner 类
- 海伦公式
- 《学习OpenCV》课后习题解答(第四章)(仅供参考)(不断更新)
- 为什么要用存储过程
- 循环队列基本构造