English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 프로그램에서는 Java에서 주어진 속성에 따라 사용자 정의 객체의 배열 리스트(ArrayList)를 정렬하는 방법을 배웁니다。
import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
프로그램을 실행할 때, 출력은 다음과 같습니다:
A Aa B X Z
위의 프로그램에서는 String 속성 customProperty를 가진 CustomObject 클래스를 정의했습니다
또한 속성을 초기화하는 생성자와 customProperty를 반환하는 getter 함수 getCustomProperty()를 추가했습니다
main() 메서드에서는 사용자 정의 객체의 배열 목록 list를 생성하고 사용하여5개의 객체가 초기화되었습니다.
목록(list)을 주어진 속성에 따라 정렬하려면 list의 sort() 메서드를 사용합니다. sort() 메서드는 정렬할 목록(결국 정렬된 목록도 같습니다)과 비교기를 받습니다.
에서는 비교기가 람다 표현식입니다
으로부터 o1과 o2에서 두 개의 객체를 가져옵니다
compareTo() 메서드를 사용하여 두 개의 객체의 customProperty를 비교합니다.
이면1의 속성이 o2의 속성이 o1의 속성이 o2의 속성이 있으면 마지막으로 음수를 반환합니다;또는 같으면 0을 반환합니다.
이를 기준으로, 목록(list)은 가장 작은 속성에서 가장 큰 속성으로 정렬되고 목록(list)에 저장됩니다.