簡體   English   中英

如何對 ArrayList 進行排序?

[英]How to sort an ArrayList?

我在 java 中有一個雙打列表,我想按降序對 ArrayList 進行排序。

輸入ArrayList如下:

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);

那會做你想做的事。 不過記得導入Collections

這是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.Collections類的 util 方法,即

Collections.sort(list)

事實上,如果你想對自定義對象進行排序,你可以使用

Collections.sort(List<T> list, Comparator<? super T> c) 

查看集合 api

使用 lambdas (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);

使用 lambda 是可能的,因為 Comparator 接口只有一個方法要實現,因此 VM 可以推斷出哪個方法正在實現。 由於可以推斷參數的類型,因此不需要說明它們(即(a, b)而不是(Double a, Double b) 。並且由於 lambda 主體只有一行,並且方法是期望返回一個值, return是推斷的,大括號不是必需的。

在 Java8 中,List 接口上有一個默認的排序方法,如果您提供了 Comparator,它將允許您對集合進行排序。 您可以輕松地對問題中的示例進行如下排序:

testList.sort((a, b) -> Double.compare(b, a));

注意:當傳遞給 Double.compare 時,lambda 中的參數會被交換,以確保排序是降序的

如果您的list包含Comparable元素,您可以使用Collections.sort(list)list進行排序。 否則,我建議您像這里那樣實現該接口:

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)因為現在列表包含 Comparable 類型的對象並且可以排序。 順序取決於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允許您傳遞定義排序邏輯的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);

你可以這樣做:

List<String> yourList = new ArrayList<String>();
Collections.sort(yourList, Collections.reverseOrder());

Collection 有一個默認的 Comparator 可以幫助你。

另外,如果你想使用一些 Java 8 的新特性,你可以這樣做:

List<String> yourList = new ArrayList<String>();
yourList = yourList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());

|*| 排序列表:

import java.util.Collections;

|=> 按升序排序:

Collections.sort(NamAryVar);

|=> 排序 Dsc 順序:

Collections.sort(NamAryVar, Collections.reverseOrder());

|*| 顛倒 List 的順序:

Collections.reverse(NamAryVar);

你可以這樣使用

ArrayList<Group> groupList = new ArrayList<>();
Collections.sort(groupList, Collections.reverseOrder());
Collections.reverse(groupList);

在 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())

例如我有一個類 Person: String name, int age ==>Constructor new Person(name,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());

訂購 List 的另一種方法是使用 Collections 框架;

在這種情況下使用 SortedSet(列表中的 bean 應該實現 Comparable,所以 Double 是可以的):

List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
   sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);

一般來說,要按列表中 bean 的屬性排序,將列表的所有元素放入 SortedMap 中,使用屬性作為鍵,然后從 SortedMap 中獲取 values()(該屬性應實現 Comparable):

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());
  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())
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM