java集合排序笔记

public class CollectionDemo implements Serializable,Comparable<CollectionDemo>{
	
	private static final long serialVersionUID = -2958090810811192128L;
	
	private int id;
	private String name;
	
	public CollectionDemo(){}
	
	public CollectionDemo(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	//方法一:继承Comparable接口,实现compareTo方法。 在随后生成集合后调用:Collections.sort(集合对象)即可实现排序
	@Override
	public int compareTo(CollectionDemo o) {
		String i1,i2;
		i1 = this.name;
		i2 = o.getName();
		return i1.compareTo(i2);
	}
	
	public static void main(String[] args) {
		CollectionDemo c1 = new CollectionDemo(1,"c1");
		CollectionDemo c2 = new CollectionDemo(2,"c2");
		CollectionDemo c3 = new CollectionDemo(3,"c3");
		CollectionDemo c4 = new CollectionDemo(4,"c4");
		CollectionDemo c5 = new CollectionDemo(5,"c5");
		
		List<CollectionDemo> lstCol = new ArrayList<CollectionDemo>();
		lstCol.add(c1);lstCol.add(c5);lstCol.add(c4);lstCol.add(c2);lstCol.add(c3);
		
		System.out.println("-------未排序------");
		for (CollectionDemo collectionDemo : lstCol) {
			System.out.println("id:"+collectionDemo.getId()+"  name:"+collectionDemo.getName());
		}
		
		System.out.println("-------排序后①------");
		Collections.sort(lstCol);
		for (CollectionDemo collectionDemo : lstCol) {
			System.out.println("id:"+collectionDemo.getId()+"  name:"+collectionDemo.getName());
		}
		
		lstCol.clear();
		System.out.println("-------清空后------");
		for (CollectionDemo collectionDemo : lstCol) {
			System.out.println("id:"+collectionDemo.getId()+"  name:"+collectionDemo.getName());
		}
		
		lstCol.add(c1);lstCol.add(c5);lstCol.add(c4);lstCol.add(c2);lstCol.add(c3);
		
		//方法二:实现Comparator的compare方法
		Collections.sort(lstCol, new Comparator<CollectionDemo>() {
			@Override
			public int compare(CollectionDemo o1, CollectionDemo o2) {
				return o2.getName().compareTo(o1.getName());
			}
		});
		
		System.out.println("-------排序后②------");
		for (CollectionDemo collectionDemo : lstCol) {
			System.out.println("id:"+collectionDemo.getId()+"  name:"+collectionDemo.getName());
		}
		
		
		//方法三:使用TreeSet实现类自动进行自然排序
		System.out.println("-------TreeSet排序后③------");
		Set<CollectionDemo> ts = new TreeSet<CollectionDemo>(); //SortedSet是TreeSet的接口
		ts.add(c1);ts.add(c5);ts.add(c4);ts.add(c2);ts.add(c3);
		for (CollectionDemo collectionDemo : ts) {
			System.out.println("id:"+collectionDemo.getId()+"  name:"+collectionDemo.getName());
		}
	}
}

 

你可能感兴趣的:(java)