1. 程式人生 > >對HashMap排序

對HashMap排序

對HashMap排序

  1. 建立自定義物件
    public class User implements Comparable<User>{
    	private Integer id;
    	private String name;
    	private Integer age;
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Integer getAge() {
    		return age;
    	}
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    	@Override
    	public String toString() {
    		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    	}
    	public User() {
    		super();
    	}
    	public User(Integer id, String name, Integer age) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.age = age;
    	}
    	@Override
    	public int compareTo(User o) {
    		return this.age - o.age;
    	}
    }
  1. 對hashmap進行排序
	@Test
	public void test01() {
		Map<Integer, User> map = new HashMap<>();
		map.put(2, new User(1, "aaa", 19));
		map.put(3, new User(4, "c", 12));
		map.put(1, new User(2, "bbbb", 17));
		map.put(4, new User(3, "dd", 22));
		Set<Entry<Integer, User>> entrySet = map.entrySet();
		List<Entry<Integer, User>> list = new ArrayList<>(entrySet);
		Collections.sort(list, new Comparator<Entry<Integer, User>>() {
			@Override
			public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
				return o1.getValue().getAge() - o2.getValue().getAge();
			}
		});
		for (Entry<Integer, User> entry : list) {
			System.out.println(entry.getKey() + "***" + entry.getValue());
		}
	}

執行結果如圖所示(按照年齡排序)

在這裡插入圖片描述