码迷,mamicode.com
首页 > 编程语言 > 详细

java:list排序

时间:2015-01-07 18:42:49      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

第一种方法:就是list中对象(bean文件)实现Comparable接口,代码如下:

package com.mapred.entity;

public class Bar implements Comparable<Bar>{
	private String id; 
	private String hexValue  ;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getHexValue() {
		return hexValue;
	}
	public void setHexValue(String hexValue) {
		this.hexValue = hexValue;
	}
	 @Override
	public int compareTo(Bar arg0) {
	    return this.getId().compareTo(arg0.getId());
	}
}

 调用

	StringBuffer buffer = new StringBuffer("");
		 Collections.sort(list);
		for(int i=0;i<list.size();i++){
			Bar bar=list.get(i);
			String lineHex=bar.getHexValue();
			buffer.append(lineHex);
		}

第二种方法,就是在重载Collections.sort方法,代码如下:

public class Person {
    private String name;
    private Integer order;
     public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getOrder() {
        return order;
    }
    public void setOrder(Integer order) {
        this.order = order;
    }
}

  调用

public static void main(String[] args) {
        List<Person> listA = new ArrayList<Person>();
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
 
        p1.setName("name1");
        p1.setOrder(1);
        p2.setName("name2");
        p2.setOrder(2);
        p3.setName("name3");
        p3.setOrder(3);
 
        listA.add(p2);
        listA.add(p1);
        listA.add(p3);
         
        Collections.sort(listA, new Comparator<Person>() {
            public int compare(Person arg0, Person arg1) {
                return arg0.getOrder().compareTo(arg1.getOrder());
            }
        });
         
        for (Person p : listA) {
            System.out.println(p.getName());
        }
    }

 

  

 

java:list排序

标签:

原文地址:http://www.cnblogs.com/kxdblog/p/4208939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!