List排序和去重

时间:2022-08-21 05:27:22
//去重和排序
		List<SysResource> sortList = new ArrayList<SysResource>();
		sortList.addAll(list);
		sortList = new ArrayList<SysResource>(new HashSet<SysResource>(sortList));// 去重
		Collections.sort(sortList, new Comparator<SysResource>() {// 排序
					@Override
					public int compare(SysResource o1, SysResource o2) {
						if (o1.getSeq() == null) {
							o1.setSeq(1000);
						}
						if (o2.getSeq() == null) {
							o2.setSeq(1000);
						}
						return o1.getSeq().compareTo(o2.getSeq());
					}
		});

List去重用了hashSet  

那么如何根据自定义字段对List排序呢。。

User类

package list;

public class User {
	private int id;
	private Integer age;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

  

List类

package list;

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

public class ListSeq {
	public static void main(String[] args) {
		List<User> list1=new ArrayList<User>();
		for(int i=0;i<5;i++){
			User user=new User();
			user.setAge(i);
			user.setId(i);
			user.setName("age"+i);
			list1.add(user);
		}
		Collections.sort(list1, new Comparator<User>() {// 排序
			@Override
			public int compare(User o1, User o2) {
				if (o1.getAge()==null) {
					o1.setAge(1000);
				}
				if (o2.getAge()== null) {
					o2.setAge(1000);
				}
				//return o2.getAge().compareTo(o1.getAge());//倒序
				return o1.getAge().compareTo(o2.getAge());//顺序
			}
		});
		System.out.println(list1.get(0).getAge());//顺序是0,倒序是4
	}

}