1. 程式人生 > >List集合的排序

List集合的排序

List集合的排序

1.對基本型別的包裝型別進行排序

@Test
	public void test01() {
		List<Integer> list = new ArrayList<>();
		list.add(3);
		list.add(2);
		list.add(1);
		list.add(4);
		System.out.println("排序前:"+list);
		Collections.sort(list);
		System.out.println("排序後:"+list);
	}

執行結果如下:

   排序前:[3, 2, 1, 4]
   排序後:[1, 2, 3, 4]

2.對自定義物件的排序

@Test
	public void test02() {
		List<User> list = new ArrayList<>();
		list.add(new User(1, "aaa", 19));
		list.add(new User(4, "c", 12));
		list.add(new User(2, "bbbb", 17));
		list.add(new User(3, "dd", 22));
		for (User user : list) {
			System.out.println(user);
		}
		System.out.println("============================");
		Collections.sort(list);
		for (User user : list) {
			System.out.println(user);
		}
		System.out.println("============================");
		Collections.sort(list, new Comparator<User>() {
			@Override
			public int compare(User o1, User o2) {
				int num = o1.getName().compareTo(o2.getName());
				return num == 0 ? o1.getAge() - o2.getAge() : num;
			}
		});
		for (User user : list) {
			System.out.println(user);
		}
	}
}

執行結果

User [id=1, name=aaa, age=19]
User [id=4, name=c, age=12]
User [id=2, name=bbbb, age=17]
User [id=3, name=dd, age=22]
============================
User [id=4, name=c, age=12]
User [id=2, name=bbbb, age=17]
User [id=1, name=aaa, age=19]
User [id=3, name=dd, age=22]
============================
User [id=1, name=aaa, age=19]
User [id=2, name=bbbb, age=17]
User [id=4, name=c, age=12]
User [id=3, name=dd, age=22]

結論:對自定義物件進行排序的時候自定義物件需要實現Comparable介面並重寫compareTo方法。或者使用Collections.sort(list, new Comparator())方法進行自定義排序。