Java 컬렉션 정렬
Java 컬렉션이 있습니다.
Collection<CustomObject> list = new ArrayList<CustomObject>();
CustomObject
이 id
필드는 현재 표시 목록 전에 그하여이 컬렉션을 정렬 할 id
.
그렇게 할 수있는 방법이 있습니까?
비교기 사용 :
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
또한을 CustomObject
구현 Comparable
하는 경우Collections.sort(list)
JDK 8에서는 구문이 훨씬 간단합니다.
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
훨씬 간단
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
가장 간단
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
분명히 초기 코드는 JDK 8에도 사용할 수 있습니다.
질문은 "Sort Collection"입니다. 따라서 Collections.sort(List<T> l, Comparator<? super T> comparator)
.
몇 가지 팁 :
컬렉션 유형 :
Comparator<String> defaultComparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
};
Collection<String> collection = getSomeStringCollection();
String[] strings = collection.toArray(new String[collection.size()]);
Arrays.sort(strings, defaultComparator);
List<String> sortedStrings = Arrays.asList(strings);
Collection<String> collection = getSomeStringCollection();
List<String> list = new ArrayList(collection);
Collections.sort(list, defaultComparator);
collection = list; // if you wish
목록 유형 :
List<String> list = getSomeStringList();
Collections.sort(list, defaultComparator);
세트 유형 :
Set<String> set = getSomeStringSet();
// Than steps like in 'For Collection type' section or use java.util.TreeSet
// TreeSet sample:
// Sorted using java.lang.Comparable.
Set<String> naturalSorted = new TreeSet(set);
Set<String> set = getSomeStringSet();
Set<String> sortedSet = new TreeSet(defaultComparator);
sortedSet.addAll(set);
Java 8 버전. 이 java.util.List#sort(Comparator<? super E> c)
방법은
List<String> list = getSomeStringList();
list.sort(defaultComparator);
또는
List<String> list = getSomeStringList();
list.sort((String o1, String o2) -> o1.compareTo(o2));
또는 Comparable을 구현하는 유형의 경우 :
List<String> list = getSomeStringList();
list.sort(String::compareTo);
Comparable을 구현하지 않는 클래스가 있지만 여전히 필드 또는 메서드에서 정렬하려는 경우 약간 다른 예가 있습니다.
Collections.sort(allMatching, new Comparator<ClassOne>() {
@Override public int compare(final ClassOne o1, final ClassOne o2) {
if (o1.getMethodToSort() > o2.getMethodToSort()) {
return 1;
} else if (o1.getMethodToSort() < o2.getMethodToSort()) {
return -1;
}
return 0;
}
});
You should implement the Comparator
interface.
example:
public class CustomComparator implements Comparator<CustomObject>
{
@Override
public int compare(CustomObject o1, CustomObject o2) {
return o1.getId().compareTo(o2.getId());
}
}
Then you can use the Collections classes Collections.sort()
method:
Collections.sort(list, new CustomComparator());
Implement the Comparable interface on your customObject.
Comparator
is the way
Also See
As of Java 8 you now can do it with a stream using a lambda:
list.stream().sorted(Comparator.comparing(customObject::getId))
.foreach(object -> System.out.println(object));
A lot of correct answers, but I haven't found this one: Collections cannot be sorted, you can only iterate through them.
Now you can iterate over them and create a new sorted something
. Follow the answers here for that.
Use sort.
You just have to do this:
All elements in the list must implement the Comparable interface.
(Or use the version below it, as others already said.)
SortedSet and Comparator. Comparator should honour the id field.
With Java 8 you have several options, combining method references and the built-in comparing
comparator:
import static java.util.Comparator.comparing;
Collection<CustomObject> list = new ArrayList<CustomObject>();
Collections.sort(list, comparing(CustomObject::getId));
//or
list.sort(comparing(CustomObject::getId));
You can use java Custom Class for the purpose of sorting.
You can also use:
Collections.sort(list, new Comparator<CustomObject>() {
public int compare(CustomObject obj1, CustomObject obj2) {
return obj1.id - obj2.id;
}
});
System.out.println(list);
참고URL : https://stackoverflow.com/questions/6957631/sort-java-collection
'IT TIP' 카테고리의 다른 글
json과 xml의 차이점은 무엇입니까 (0) | 2020.10.22 |
---|---|
4KB에 몇 개의 문자를 저장할 수 있습니까? (0) | 2020.10.22 |
mockito 테스트를 실행할 때 WrongTypeOfReturnValue Exception이 발생합니다. (0) | 2020.10.22 |
추적 출력을 콘솔로 리디렉션 (0) | 2020.10.22 |
WPF의 크기 조정 가능한 창에서 최소화 및 최대화를 제거하려면 어떻게합니까? (0) | 2020.10.22 |