java多条件排序_集合操作--多条件排序

[java]代码库1.Main

package s0223多条件排序;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Date;

import java.util.List;

public class Main {

public static void main(String[] args) {

List news=new ArrayList();

news.add(new NewsItem("中国登上钓鱼岛",100,new Date(System.currentTimeMillis() ) ) );

news.add(new NewsItem("中国GDP总量",40,new Date(System.currentTimeMillis() ) ) );

news.add(new NewsItem("美国总统与xx会晤",60, new Date(System.currentTimeMillis() ) ) );

System.out.println("排序前:"+news);

Collections.sort(news);

//因为news中的元素都是Comparable的实现类的实例,所以默认使用指定的Comparator

//如果使用comparator的实现类,那么要指定comparator

System.out.println("排序后:"+news);

}

}

2.NewsItem类,在这个类中定义了排序优先级和排序顺序

package s0223多条件排序;

import java.text.SimpleDateFormat;

//新闻按时间降序,点击量升序,标题降序

import java.util.Date;

public class NewsItem implements java.lang.Comparable{

private String title;

private int hit;

private Date pubTime;

public NewsItem(){}

public NewsItem(String title, int hit, Date pubTime)

{

super();

this.title = title;

this.hit = hit;

this.pubTime = pubTime;

}

//新闻按时间降序,点击量升序,标题降序,3个if嵌套,规定了排序的优先级

public int compareTo(NewsItem o)

{

int result=0;

result=-this.pubTime.compareTo(o.pubTime);//加了- 变成降序

if(result==0)

{

result=this.hit-o.hit;

if(result==0)

{

result=this.title.compareTo(o.title);

}

}

return result;

}

public String toString()

{

StringBuilder sb=new StringBuilder();

sb.append(" 标题:").append(this.title);

sb.append(" 时间:").append(new SimpleDateFormat("yyyy-MM-dd").format(this.pubTime));

sb.append(" 点击量:").append(this.hit).append("\n");

String str=sb.toString();

return str;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public int getHit() {

return hit;

}

public void setHit(int hit) {

this.hit = hit;

}

public Date getPubTime() {

return pubTime;

}

public void setPubTime(Date pubTime) {

this.pubTime = pubTime;

}

}

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值