第一种方法:就是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()); } }
时间: 2024-09-30 21:29:58