JAVA对List列表排序_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JAVA对List列表排序

JAVA对List列表排序

 2017/8/2 12:38:59  lijun0349  程序员俱乐部  我要评论(0)
  • 摘要:NewsManager.javapackagetest;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;publicclassNewsManager{/***@paramargs*/publicstaticvoidmain(String[]args){Listnewss=getNewsList();for(inti=0;i<newss
  • 标签:list Java
class="java" name="code">
NewsManager.java

package 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());
		}
	}

	@SuppressWarnings("unchecked")
	public static List getNewsList() {
		List list = new ArrayList();

		News news1 = new News();
		news1.setHits(1);
		news1.setId(1);
		news1.setTitle("2017年07月31日 18:39");
		list.add(news1);

		News news2 = new News();
		news2.setHits(7);
		news2.setId(2);
		news2.setTitle("2017年07月31日 12:54");
		list.add(news2);

		News news3 = new News();
		news3.setHits(3);
		news3.setId(3);
		news3.setTitle("2017年07月31日 13:04");
		list.add(news3);

		News news4 = new News();
		news4.setHits(5);
		news4.setId(4);
		news4.setTitle("2017年07月31日 12:49");
		list.add(news4);

		// 按点击数倒序
		Collections.sort(list, new Comparator<News>() {
			public int compare(News arg0, News arg1) {
				String hits0 = arg0.getTitle();
				String hits1 = arg1.getTitle();
				if (hits1.compareTo(hits0) > 0) {
					return 1;
				} else if (hits1.compareTo(hits0) == 0) {
					return 0;
				} else {
					return -1;
				}
			}
		});
		return list;
	}
}

==========================================================
News.java

package test;

public class News {
	private int id;
	private String title;
	private int hits;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getHits() {
		return hits;
	}
	public void setHits(int hits) {
		this.hits = hits;
	}
}
发表评论
用户名: 匿名