如何把一个list集合中的对象,按对象的一个属性排序

u010052077 2013-10-26 09:53:18
面试题,不会做啊,求大神指点
...全文
13999 5 打赏 收藏 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhuweisyyc 2013-10-26
  • 打赏
  • 举报
回复
引用 2 楼 u010052077 的回复:
[quote=引用 1 楼 zhuweisyyc 的回复:] [quote=引用 楼主 u010052077 的回复:] 面试题,不会做啊,求大神指点
Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { // TODO Auto-generated method stub return 0; } });[/quote] 还是不懂啊 ,大哥写个注释吧[/quote] list 是你要排序的。 Collections 是集合的公共类,提供各种工具,其中提供了排序方法。 Collections.sort(),方法两个参数,1,要排序的集合,2.排序方式 下面是匿名内部类,实现了排序借口,你也可以写外面。 Comparator c=new Comparator<T>() { @Override public int compare(T o1, T o2) { // TODO Auto-generated method stub return 0; } }
u010052077 2013-10-26
  • 打赏
  • 举报
回复
引用 1 楼 zhuweisyyc 的回复:
[quote=引用 楼主 u010052077 的回复:] 面试题,不会做啊,求大神指点
Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { // TODO Auto-generated method stub return 0; } });[/quote] 还是不懂啊 ,大哥写个注释吧
zhuweisyyc 2013-10-26
  • 打赏
  • 举报
回复
引用 楼主 u010052077 的回复:
面试题,不会做啊,求大神指点
Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { // TODO Auto-generated method stub return 0; } });
  • 打赏
  • 举报
回复
import java.util.Set ; import java.util.TreeSet ; class Person implements Comparable<Person>{ private String name ; private int age ; public Person(String name,int age){ this.name = name ; this.age = age ; } public String toString(){ return "姓名:" + this.name + ";年龄:" + this.age ; } public int compareTo(Person per){ if(this.age>per.age){ return 1 ; }else if(this.age<per.age){ return -1 ; }else{ return this.name.compareTo(per.name) ; // 调用String中的compareTo()方法 } } }; public class TreeSetDemo04{ public static void main(String args[]){ Set<Person> allSet = new TreeSet<Person>() ; allSet.add(new Person("张三",30)) ; allSet.add(new Person("李四",31)) ; allSet.add(new Person("王五",32)) ; allSet.add(new Person("王五",32)) ;//重复元素,不能加入 allSet.add(new Person("王五",32)) ;//重复元素,不能加入 allSet.add(new Person("赵六",33)) ; allSet.add(new Person("孙七",33)) ; System.out.println(allSet) ; } };
qw4286874 2013-10-26
  • 打赏
  • 举报
回复
对象没贴出来
	public void sortTest1(){
		List<SortBean> list = new ArrayList<SortBean>();
		SortBean bean = null;
		Random r = new Random();
		for(int i=0;i<6;i++){
			bean = new SortBean();
			bean.setId(i);
			bean.setName("测试"+i);
			bean.setAge(r.nextInt(100));
			list.add(bean);
		}
//		System.out.println(JSONArray.fromObject(list));
		ComparatorChain chain = new ComparatorChain();
		chain.addComparator(new BeanComparator("age"),true);//true,fase正序反序
//		chain.addComparator(new BeanComparator("name"));
//		chain.addComparator(new BeanComparator("age"));
		Collections.sort(list,chain);
		System.out.println(JSONArray.fromObject(list));
	}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧