集合sort方法的使用

Collections.sort方法可以对集合进行排序,它有两个参数arg0:要排序的集合;arg1:实现了比较接口的类。下面是具体代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;

public class LinkSort implements Comparator<LinkSort>{
	Logger logger=Logger.getLogger(LinkSort.class); 
	public LinkSort(){
		super();
	}
	public LinkSort(String key,String url,int linkCount){
		this.key=key;
		this.url=url;
		this.linkCount=linkCount;
	}
	private String key;
	private String url;
	
	private int linkCount;
	public int getLinkCount() {
		return linkCount;
	}
	public void setLinkCount(int linkCount) {
		this.linkCount = linkCount;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	/**
	 * 排序方法
	 * 根据点击次数进行排序   linkCount
	 * **/
	@Override
	public int compare(LinkSort arg0,LinkSort arg1){
		if(arg0.getLinkCount()>=arg1.getLinkCount()){
			return 0;
		}else{
			return 1;
		}
	}
	/**
	 * 生成json格式
	 * @return String json 格式  {UserManager=/wmba/user/user_queryUserInfos.action}
	 **/
	public String linkSortToJSON(List<LinkSort> list){
		if(list.size()>0){
			//排序
			Collections.sort(list, new LinkSort());
			StringBuffer sb=new StringBuffer();
			sb.append("{");
			for(LinkSort ls : list){
				sb.append(ls.getKey()).append(":").append(ls.getUrl()).append(ls.getLinkCount()).append(",\n");
			}
			//去掉最后一个","号   并加上"}"
			String temp=sb.toString().substring(0,sb.toString().length()-1)+"}";
			logger.debug(temp);
			return temp;
		}
		return "false";
	}
	public static void main(String[] args) {
		List<LinkSort> list=new ArrayList<LinkSort>();
		list.add(new LinkSort("en_US_link","/wmba/user/user_addUser2.action",3));
		list.add(new LinkSort("en_US_link","/wmba/user/user_addUser1.action",6));
		list.add(new LinkSort("en_US_link","/wmba/user/user_addUser3.action",1));
		list.add(new LinkSort("en_US_link","/wmba/user/user_addUser4.action",2));
		list.add(new LinkSort("en_US_link","/wmba/user/user_addUser5.action",5));
		
		LinkSort linksort=new LinkSort();
		
		System.out.println(linksort.linkSortToJSON(list));
	}
}

最后输出:

{en_US_link:/wmba/user/user_addUser1.action6,
en_US_link:/wmba/user/user_addUser5.action5,
en_US_link:/wmba/user/user_addUser2.action3,
en_US_link:/wmba/user/user_addUser4.action2,
en_US_link:/wmba/user/user_addUser3.action1,}

你可能感兴趣的:(sort)