Java 如何对 ArrayList 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16252269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:01:48  来源:igfitidea点击:

How to sort an ArrayList?

javasortingarraylistcollections

提问by Himanshu

I have a List of doubles in java and I want to sort ArrayList in descending order.

我在 java 中有一个双精度列表,我想按降序对 ArrayList 进行排序。

Input ArrayList is as below:

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

The out put should be like this

输出应该是这样的

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

采纳答案by Doorknob

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collectionsthough!

那会做你想做的。Collections不过记得导入哦!

Here is the documentation for Collections.

这是Collections.

回答by M Sach

Use util method of java.util.Collectionsclass, i.e

使用java.util.Collections类的util 方法,即

Collections.sort(list)

In fact, if you want to sort custom object you can use

事实上,如果你想对自定义对象进行排序,你可以使用

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

see collections api

见集合api

回答by M Sach

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

    }
}

回答by Yuriy

You can use Collections.sort(list)to sort listif your listcontains Comparableelements. Otherwise I would recommend you to implement that interface like here:

如果您的包含元素,您可以使用Collections.sort(list)排序。否则,我会建议您像这样实现该接口:listlistComparable

public class Circle implements Comparable<Circle> {}

and of course provide your own realization of compareTomethod like here:

当然,提供您自己的compareTo方法实现,如下所示:

@Override
    public int compareTo(Circle another) {
        if (this.getD()<another.getD()){
            return -1;
        }else{
            return 1;
        }
    }

And then you can again use Colection.sort(list)as now list contains objects of Comparable type and can be sorted. Order depends on compareTomethod. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.htmlfor more detailed information.

然后你可以再次使用,Colection.sort(list)因为现在列表包含 Comparable 类型的对象并且可以排序。顺序取决于compareTo方法。查看此https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html以获取更多详细信息。

回答by Franklin Okeme

if you are using Java SE 8, then this might be of help.

如果您使用的是 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);

回答by Matt

Collections.sortallows you to pass an instance of a Comparatorwhich defines the sorting logic. So instead of sorting the list in natural order and then reversing it, one can simply pass Collections.reverseOrder()to sortin order to sort the list in reverse order:

Collections.sort允许您传递Comparator定义排序逻辑的 a 实例。因此,不是按自然顺序对列表进行排序然后将其反转,而是可以简单地传递Collections.reverseOrder()sort以相反顺序对列表进行排序:

// import java.util.Collections;
Collections.sort(testList, Collections.reverseOrder());

As mentioned by @Marco13, apart from being more idiomatic (and possibly more efficient), using the reverse order comparator makes sure that the sort is stable (meaning that the order of elements will not be changed when they are equal according to the comparator, whereas reversing will change the order)

正如@Marco13 所提到的,除了更惯用(并且可能更有效)之外,使用逆序比较器可确保排序稳定(这意味着当元素根据比较器相等时,它们的顺序不会改变,而倒车会改变顺序)

回答by manikant gautam

You can use like that

你可以这样使用

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

回答by bong jae choe

Descending:

降序:

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

回答by cyrus

Using lambdas (Java8), and stripping it down to the barest of syntax (the JVM will infer plentyin this case), you get:

使用 lambdas (Java8),并将其剥离为最简单的语法(在这种情况下,JVM 将推断出很多),您将得到:

Collections.sort(testList, (a, b) -> b.compareTo(a));

A more verbose version:

更详细的版本:

// Implement a reverse-order Comparator by lambda function
Comparator<Double> comp = (Double a, Double b) -> {
    return b.compareTo(a);
};

Collections.sort(testList, comp);

The use of a lambda is possible because the Comparator interface has only a single method to implement, so the VM can infer which method is implementing. Since the types of the params can be inferred, they don't need to be stated (i.e. (a, b)instead of (Double a, Double b). And since the lambda body has only a single line, and the method is expected to return a value, the returnis inferred and the braces aren't necessary.

使用 lambda 是可能的,因为 Comparator 接口只有一个方法要实现,所以 VM 可以推断出哪个方法正在实现。由于可以推断参数的类型,因此不需要说明它们(即(a, b)代替(Double a, Double b). 并且由于 lambda 主体只有一行,并且该方法预计会返回一个值,因此return推断出的和大括号没有必要。

回答by robjwilkins

With Java8 there is a default sort method on the List interface that will allow you to sort the collection if you provide a Comparator. You can easily sort the example in the question as follows:

在 Java8 中,List 接口上有一个默认的排序方法,如果您提供比较器,它将允许您对集合进行排序。您可以轻松地对问题中的示例进行排序,如下所示:

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

Note: the args in the lambda are swapped when passed in to Double.compare to ensure the sort is descending

注意:传递给 Double.compare 时,将交换 lambda 中的 args 以确保排序是降序的