Cách sắp xếp mảng trong Java

Ví du 1: Sắp xếp theo điểm

	public void sortGpa() {
		// Cach 1: Khai báo bình thường
		Collections.sort(studentlist, new Comparator<StudentModel>() {

			@Override
			public int compare(StudentModel o1, StudentModel o2) {
				if (o1.getGpa() < o2.getGpa()) return -1;
				return 1;
			}
		});

		// Cach 2: khai báo cấu trúc rút gọn
		Collections.sort(studentlist, (o1, o2) -> {
			if (o1.getGpa() < o2.getGpa())
				return -1;
			return 1;
		});
		studentlist.forEach((list) -> {
			list.display();
		});
	}

Ví dụ 2: Sắp xếp theo Name.

	public void sortName() {
//Khai báo kiểu bình thường
		Collections.sort(studentlist, new Comparator<StudentModel>() {

			@Override
			public int compare(StudentModel o1, StudentModel o2) {
				return o1.getName().compareTo(o2.getName());
			}
		});
//Khai báo kiểu rút gọn
		Collections.sort(studentlist, (o1, o2) -> o1.getName().compareTo(o2.getName()));
		studentlist.forEach((list) -> {
			list.display();
		});
	}

Chào mừng bạn đến với blog của tôi! Đây là nơi tôi chia sẻ những trải nghiệm, suy nghĩ và kiến thức mà tôi học được trong cuộc sống và công việc. Hy vọng bạn sẽ tìm thấy điều gì đó hữu ích và thú vị tại đây.

Design a site like this with WordPress.com
Get started