나는 내가 원하는 목록이 복식 자바와 라일리스트 정렬하려면 내림차순으로.
라일리스트 는 다음과 같이 입력:
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);
할 수 있는 그리웠댔지. '모음' 너희에게베풀어진 가져오기할 표시되어도!
[다음은 설명서 '모음'] (https://docs.oracle.com/javase/10/docs/api/java/util/Collections.html # 정렬함으로써 (제바스티라자리스트)).
내림차순을:
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;
}
});
예를 들어, 자바 가상 머신 (jvm) 에 8 단축시킵니다 이 will do the magic
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
람다 (Java8) 및 it down to the arts) 를 사용하여 구문 (이하 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);
이 때문에 가능한 단 하나의 람다 (λ) 를 구현하는 방법은 추론할 수 있다, 그래서 vmo 비교자 인터페이스입니다 어떤 방법을 구축하고 있습니다. 이후, 그들은 params 유형을 유추 할 수 있다고 don& # 39, t (즉, ' (a, b)' 대신 ' (연산뿐 더블 a, b)'. 이후 라인 및 방법 및 람다 바디입니다 하나뿐이며, 이 값을 반환하는 것으로 보인다 '는' 반품하십시오 유추 및 괄호는 aren& # 39, t 필요하다.
사용할 수 있습니다 (목록) '' 콜레스티온s.소르 정렬하려면 경우 '목록' '목록' '비슷한' 요소가 포함되어 있습니다. 그렇지 않으면 여기 있는 것과 꼭 이래야겠어요 추천합니까 인터페이스입니다 구현할 수 있습니다.
public class Circle implements Comparable<Circle> {}
물론 실현 '' 같은 방법을 İç 제공하십시오 콩파레토 있습니다.
@Override
public int compareTo(Circle another) {
if (this.getD()<another.getD()){
return -1;
}else{
return 1;
}
}
그럼 이제 다시 사용할 수 있는 '콜스션.소르 (목록)' 도 비슷한 객체에는 목록에는 유형 및 정렬할 수 있습니다. '방법' 주문하십시오 콩파레토 따라 달라집니다. 자세한 정보는 https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html 확인할 수 있습니다.
'콜레스티온s.소르' a '정렬' 전달하십시오 인스턴스입니다 비교자 정의할 수 있다. 그래서 대신 정렬 목록에서 주문하십시오 반전합니다 한 후 이를 쉽게 할 수 있습니다 '자연' 을 위해 정렬하려면 전달하십시오 콜레스티언스트레버스러더 () '' 목록을 정렬하려면 역뱡향으로 순서:
// 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;
}
}
자바 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);
이렇게 할 수 있습니다.
List<String> yourList = new ArrayList<String>();
Collections.sort(yourList, Collections.reverseOrder());
수집이 경쟁자의 도움을 줄 수 있는 기본.
또한 일부 jave 8 개의 새로운 기능을 사용하려면, 그렇게 할 수 있습니다.
List<String> yourList = new ArrayList<String>();
yourList = yourList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
이것은 파선-짧은 컨닝 지 다루는 전형적인 사례:
// 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))
이렇게 사용할 수 있습니다.
ArrayList<Group> groupList = new ArrayList<>();
Collections.sort(groupList, Collections.reverseOrder());
Collections.reverse(groupList);
이제 8 훨씬 쉽게 자바 가상 머신 (jvm) 에 있다.
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())
예를 들어 I have a 클래스 사람: Int = > 구체화하십시오 이름, 나이, 새로운 사람을 구성자를 (이름, 나이)
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]]
}
1 와 [Eclipse 컬렉션] 정렬하려면 프리미티브 연산뿐 목록을 만들 수 있습니다 후 역동기화 迈向 넣어 내림차순을 주문. 이 방법을 위해 복싱 복식.
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);
'A', ', 다음, Double> 스케쳐내 List< 협력할 것이라고 말했다.
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> 유형으로 ',', ',' 유틸리티 클래스를 사용하여 다음과 같이 라일리스티테라치 초기화하지 및 목록을 정렬할 수 있습니다.
ArrayList<Double> arrayList =
ArrayListIterate.sortThis(
new ArrayList<>(objectList), Collections.reverseOrder());
arrayList.forEach(System.out::println);
참고: 나는 커미터는 장치당 Eclipse 컬렉션.