เมธอด Collections.sort() ใช้เรียงลำดับ ArrayList แบบอ름ช่วง (ascending) ส่วน Collections.reverse() ใช้กลับลำดับ ต้อง import java.util.Collections ก่อนใช้งาน
Java ArrayList คืออะไร
ArrayList เป็นคลาสที่สร้างอาร์เรย์ขนาดปรับเปลี่ยนได้ (resizable array) เป็นการ implement interface List ให้เข้าถึงเมธอดจัดการข้อมูลต่างๆ ได้
เมธอด Collections.sort()
เรียงลำดับข้อมูลใน ArrayList แบบ ascending (น้อยไปมาก / A-Z)
import java.util.Collections; Collections.sort(listName);
ตัวอย่าง: เรียงชื่อนักเรียนตามตัวอักษร
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Lindsay");
students.add("Peter");
students.add("Lucas");
students.add("Athena");
System.out.println("Student list: " + students);
Collections.sort(students);
System.out.println("Sorted student list: " + students);
}
}
ผลลัพธ์:
Student list: [Peter, Lindsay, Lucas, Athena] Sorted student list: [Athena, Lindsay, Lucas, Peter]
หมายเหตุ: sort() จะเปลี่ยนลำดับใน list เดิม ไม่ได้สร้าง list ใหม่
เมธอด Collections.reverse()
กลับลำดับข้อมูลใน ArrayList ใช้ร่วมกับ sort() เพื่อเรียง descending (มากไปน้อย / Z-A)
Collections.sort(students); // เรียง A-Z ก่อน Collections.reverse(students); // แล้วค่อยกลับเป็น Z-A
ตัวอย่าง: เรียงชื่อนักเรียนแบบ descending
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Lindsay");
students.add("Peter");
students.add("Lucas");
students.add("Athena");
System.out.println("Student list: " + students);
Collections.sort(students);
Collections.reverse(students);
System.out.println("Sorted student list: " + students);
}
}
ผลลัพธ์:
Student list: [Lindsay, Peter, Lucas, Athena] Sorted student list: [Peter, Lucas, Lindsay, Athena]
สรุป
Collections.sort()- เรียง ascendingCollections.reverse()- กลับลำดับ- ใช้ร่วมกันได้ descending order