목록/어레이 목록 정렬 방법
java의 double 목록이 있는데 Array List를 내림차순으로 정렬하고 싶습니다.
입력 Array List는 다음과 같습니다.
List<Double> testList = new ArrayList();
testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);
아웃풋은 이 상태여야 합니다.
0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1
Collections.sort(testList);
Collections.reverse(testList);
그것으로 네가 원하는 대로 할 수 있을 거야. 말고 Import해 .Collections★★★★★★★★★★★★★★★★★★!
의 매뉴얼을 다음에 나타냅니다.
내림차순:
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});
예를 들어, Java 8에서 매직이 실행됩니다.
List<Double> testList = new ArrayList();
testList.sort(Comparator.naturalOrder());
그러나 정렬 중인 개체의 일부 필드를 기준으로 정렬하려면 다음을 사용하여 쉽게 정렬할 수 있습니다.
testList.sort(Comparator.comparing(ClassName::getFieldName));
또는
testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());
또는
testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());
출처 : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
java.util의 util 메서드를 사용합니다.컬렉션 클래스, 즉
Collections.sort(list)
실제로 사용자 지정 개체를 정렬하려면
Collections.sort(List<T> list, Comparator<? super T> c)
"collections api" 참조
lamdas(Java8)를 사용하여 구문(이 경우 JVM이 충분히 추론할 수 있음)의 맨 아래 부분까지 제거하면 다음과 같은 결과를 얻을 수 있습니다.
Collections.sort(testList, (a, b) -> b.compareTo(a));
보다 상세한 버전:
// Implement a reverse-order Comparator by lambda function
Comparator<Double> comp = (Double a, Double b) -> {
return b.compareTo(a);
};
Collections.sort(testList, comp);
Lamda를 사용할 수 있는 것은 Comparator 인터페이스에는 구현할 수 있는 방법이1개뿐이기 때문에 VM은 어떤 방법이 구현되어 있는지 유추할 수 있습니다.할 수 있기 패러머의 종류는 유추할 수 있습니다(예: '파람의 종류', '파람의 종류', '파람의 종류', '파람의 종류', '파람의 종류', '파람의 종류', '파람의 종류', '파람의 종류',(a, b)(Double a, Double b)줄밖에 에 람다 본체는 을 반환하지 않습니다.return을 사용법
Java8에서는 List 인터페이스 상에 기본 정렬 방식이 있으며, 이를 통해 Comparator를 제공할 경우 컬렉션을 정렬할 수 있습니다.질문의 예는 다음과 같이 쉽게 정렬할 수 있습니다.
testList.sort((a, b) -> Double.compare(b, a));
주의: 람다 내의 arg는 Double.로 전달되었을 때 스와프되어 정렬이 내림차순으로 되어 있는지 확인합니다.
하시면 됩니다.Collections.sort(list)list listComparable그렇지 않은 에는 다음과 구현하는 .
public class Circle implements Comparable<Circle> {}
을 얻을 수 .compareTo다음과 같이 합니다.
@Override
public int compareTo(Circle another) {
if (this.getD()<another.getD()){
return -1;
}else{
return 1;
}
}
사용하시면 .Colection.sort(list)현재 목록에는 Comparible 유형의 개체가 포함되어 있으며 정렬할 수 있습니다.에 따라 .compareTo방법.상세한 것에 대하여는, 이 https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html 를 참조해 주세요.
다음은 일반적인 사례를 다루는 짧은 치트시트입니다.
import static java.util.Comparator.comparing;
// sort
list.sort(naturalOrder());
// sort (reversed)
list.sort(reverseOrder());
// sort by field
list.sort(comparing(Type::getField));
// sort by field (reversed)
list.sort(comparing(Type::getField).reversed());
// sort by int field
list.sort(comparingInt(Type::getIntField));
// sort by double field (reversed)
list.sort(comparingDouble(Type::getDoubleField).reversed());
// sort by nullable field (nulls last)
list.sort(comparing(Type::getNullableField, nullsLast(naturalOrder())));
// two-level sort
list.sort(comparing(Type::getField1).thenComparing(Type::getField2));
Collections.sort allows of of의 인스턴스를 전달할 수 .Comparator정렬 로직을 정의합니다. 목록을 하는 그냥 넘어가면 요.Collections.reverseOrder()로.sort목록을 역순으로 정렬하려면:
// import java.util.Collections;
Collections.sort(testList, Collections.reverseOrder());
@Marco13에서 설명한 바와 같이, 보다 관용적인(그리고 보다 효율적일 수 있음) 외에, 역순서 비교기를 사용하면 정렬이 안정적입니다(즉, 비교기에 따라 요소가 같을 때 순서는 변경되지 않는 반면 역순서는 순서가 변경됩니다.
//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee) synchronizedListOne).name
.compareTo(((Employee) synchronizedListTwo).name);
}
});
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/
// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}
}
}
class Employee {
String name;
Employee(String name) {
this.name = name;
}
}
Java SE 8을 사용하는 경우 도움이 될 수 있습니다.
//create a comparator object using a Lambda expression
Comparator<Double> compareDouble = (d1, d2) -> d1.compareTo(d2);
//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(compareDouble));
//print the sorted list using method reference only applicable in SE 8
testList.forEach(System.out::println);
|*| 목록 정렬:
import java.util.Collections;
|=> Asc 순서 정렬:
Collections.sort(NamAryVar);
|=> DSC 순서 정렬:
Collections.sort(NamAryVar, Collections.reverseOrder());
|*| 목록 순서를 바꿉니다.
Collections.reverse(NamAryVar);
JAVA 8에서는 이제 훨씬 쉬워졌습니다.
List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase = alphaNumbers.stream()
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]
·이것을 반대로 사용하는 경우
.sorted(Comparator.reverseOrder())
다음과 같이 할 수 있습니다.
List<String> yourList = new ArrayList<String>();
Collections.sort(yourList, Collections.reverseOrder());
컬렉션에는 이를 지원하는 기본 Comparator가 있습니다.
또, Java 8 의 신기능을 사용하는 경우는, 다음과 같이 할 수 있습니다.
List<String> yourList = new ArrayList<String>();
yourList = yourList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
그렇게 써도 돼
ArrayList<Group> groupList = new ArrayList<>();
Collections.sort(groupList, Collections.reverseOrder());
Collections.reverse(groupList);
예를 들어, 클래스 Person:문자열명, int age ==> 컨스트럭터 신규인물(이름, 연령)
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public void main(String[] args){
Person ibrahima=new Person("Timera",40);
Person toto=new Person("Toto",35);
Person alex=new Person("Alex",50);
ArrayList<Person> myList=new ArrayList<Person>
Collections.sort(myList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
// return p1.age+"".compareTo(p2.age+""); //sort by age
return p1.name.compareTo(p2.name); // if you want to short by name
}
});
System.out.println(myList.toString());
//[Person [name=Alex, age=50], Person [name=Timera, age=40], Person [name=Toto, age=35]]
Collections.reverse(myList);
System.out.println(myList.toString());
//[Person [name=Toto, age=35], Person [name=Timera, age=40], Person [name=Alex, age=50]]
}
ArrayList의 ID를 기준으로 객체를 정렬해야 하는 경우 java8 스트림을 사용합니다.
List<Person> personList = new ArrayList<>();
List<Person> personListSorted =
personList.stream()
.sorted(Comparator.comparing(Person::getPersonId))
.collect(Collectors.toList());
Eclipse Collections를 사용하여 기본 이중 목록을 만들고 정렬한 다음 역순으로 정렬하여 내림차순으로 정렬할 수 있습니다.이 접근방식은 복식 복식 복싱을 피할 수 있을 것이다.
MutableDoubleList doubleList =
DoubleLists.mutable.with(
0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
.sortThis().reverseThis();
doubleList.each(System.out::println);
필요한 경우List<Double>, 다음과 같이 처리됩니다.
List<Double> objectList =
Lists.mutable.with(
0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
.sortThis(Collections.reverseOrder());
objectList.forEach(System.out::println);
유형을 다음과 같이 유지하려면ArrayList<Double>를 사용하여 목록을 초기화 및 정렬할 수 있습니다.ArrayListIterate유틸리티 클래스는 다음과 같습니다.
ArrayList<Double> arrayList =
ArrayListIterate.sortThis(
new ArrayList<>(objectList), Collections.reverseOrder());
arrayList.forEach(System.out::println);
주의: 저는 Eclipse Collections의 커밋입니다.
다음 행은 두께를 나타냅니다.
testList.sort(Collections.reverseOrder());
yearList = arrayListOf()
for (year in 1950 until 2021) {
yearList.add(year)
}
yearList.reverse()
val list: ArrayList<String> = arrayListOf()
for (year in yearList) {
list.add(year.toString())
}
목록을 주문하는 다른 방법은 컬렉션 프레임워크를 사용하는 것입니다.
이 경우 SortedSet을 사용합니다(목록의 빈은 Comparible을 구현해야 하므로 Double은 OK).
List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);
일반적으로 목록의 빈 속성을 기준으로 정렬하려면 Atribute를 키로 사용하여 목록의 모든 요소를 SortedMap에 넣은 다음 SortedMap에서 값()을 가져옵니다(Atribute는 Comparible을 구현해야 합니다).
List<Bean> testList;
...
SortedMap<AttributeType,Bean> sortedMap= new TreeMap<AttributeType, Bean>();
for(Bean bean : testList) {
sortedMap.put(bean.getAttribute(),bean);
}
orderedList=new ArrayList(sortedMap.values());
언급URL : https://stackoverflow.com/questions/16252269/how-to-sort-a-list-arraylist
'source' 카테고리의 다른 글
| GCC에서 생성된 asm은 어떻게 컴파일합니까? (0) | 2022.08.31 |
|---|---|
| vue cli - 수집되지 않은 구문 오류:예기치 않은 토큰 < (0) | 2022.08.31 |
| JPA에서 발행한SQL 쿼리를 표시하는 방법 (0) | 2022.08.31 |
| javadoc에서 메서드 파라미터에 참조를 추가하는 방법 (0) | 2022.08.31 |
| C 디폴트 인수 (0) | 2022.08.31 |