java实现List中对象排序的方法
程序员文章站
2024-03-07 19:22:45
本文实例讲述了java实现list中对象排序的方法。分享给大家供大家参考,具体如下:
package com.test;
import java.util.a...
本文实例讲述了java实现list中对象排序的方法。分享给大家供大家参考,具体如下:
package com.test; import java.util.arraylist; import java.util.collections; import java.util.comparator; import java.util.list; public class newsmanager { /** * @param args */ public static void main(string[] args) { list newss=getnewslist(); for(int i=0;i<newss.size();i++) { news news=(news)newss.get(i); system.out.println("id:"+news.getid()); system.out.println("title:"+news.gettitle()); system.out.println("hits:"+news.gethits()); } } public static list getnewslist() { list list=new arraylist(); news news1=new news(); news1.sethits(1); news1.setid(1); news1.settitle("test1"); list.add(news1); news news2=new news(); news2.sethits(7); news2.setid(2); news2.settitle("test2"); list.add(news2); news news3=new news(); news3.sethits(3); news3.setid(3); news3.settitle("test3"); list.add(news3); news news4=new news(); news4.sethits(5); news4.setid(4); news4.settitle("test4"); list.add(news4); // 按点击数倒序 collections.sort(list, new comparator<news>() { public int compare(news arg0, news arg1) { int hits0 = arg0.gethits(); int hits1 = arg1.gethits(); if (hits1 > hits0) { return 1; } else if (hits1 == hits0) { return 0; } else { return -1; } } }); return list; } }
希望本文所述对大家java程序设计有所帮助。