답변:
OP 가 제공하는 답변 이 최선이 아닙니다. 이 새로운를 생성으로는 비효율적입니다 List 및 불필요한 새로운 배열. 또한 일반 배열과 관련된 유형 안전 문제로 인해 "확인되지 않은"경고가 발생합니다.
대신 다음과 같이 사용하십시오.
public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
List<T> list = new ArrayList<T>(c);
java.util.Collections.sort(list);
return list;
}
사용법 예는 다음과 같습니다.
Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
...
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);
Util클래스는 asSortedList()내가 작성한 메소드 를 포함하는 클래스입니다 . 즉, Util클래스를 직접 작성하고 해당 코드를 클래스에 넣습니다.
정렬 된 세트 :
return new TreeSet(setIWantSorted);
또는:
return new ArrayList(new TreeSet(setIWantSorted));
Set? 이기 때문에 입력 값이 같은 객체를 어떻게 가질 수 있습니까?
new TreeSet허용 하므로 언급 할 가치가 있습니다. 이 답변을 읽는 모든 사람이 원래 질문에 묻더라도을 사용 하지는 않습니다. CollectionSetSet
List myList = new ArrayList(collection);
Collections.sort(myList);
… 그러나 트릭을해야합니다. 해당되는 경우 Generics로 플레이버를 추가하십시오.
Comparable하고 재정의 할 수 있습니다 compareTo.
정렬 구현을 제공하기 위해 Comparator 또는 Comparable 인터페이스를 사용하는 것이 항상 안전합니다 (오브젝트가 기본 데이터 유형의 String 또는 Wrapper 클래스가 아닌 경우). 이름을 기준으로 직원을 정렬하기위한 비교기 구현의 예로
List<Employees> empList = new LinkedList<Employees>(EmpSet);
class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
}
Collections.sort(empList , new EmployeeComparator ());
Comparator는 동일한 객체에 대해 다른 정렬 알고리즘이 필요할 때 유용합니다 (예 : emp name, emp salary 등). 필요한 객체에 대한 비교 가능한 인터페이스를 사용하여 단일 모드 정렬을 구현할 수 있습니다.
이를 수행하는 단일 방법은 없습니다. 이것을 사용하십시오 :
@SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
T[] array = collection.toArray(
(T[])new Comparable[collection.size()]);
Arrays.sort(array);
return Arrays.asList(array);
}
TreeSet sortedset = new TreeSet();
sortedset.addAll(originalset);
list.addAll(sortedset);
여기서 originalset = 정렬되지 않은 세트 및 list = 반환 될 목록