当前位置: 首页 > 工具软件 > SortIt > 使用案例 >

Java集合sort()

黄弘盛
2023-12-01

Today we will look into Java Collections sort method. While working with Collections in java, more than often we need to sort the data.

今天,我们将研究Java Collections的排序方法。 在Java中使用Collections时 ,我们比以往更需要对数据进行排序。

Java集合sort() (Java Collections sort())

Java Collections class provides us with a very convenient method Collections.sort() to sort all List implementations such as LinkedList and ArrayList.

Java Collections类为我们提供了一个非常方便的Collections.sort()方法来对所有List实现(如LinkedListArrayList Collections.sort()进行排序。

There are two overloaded Collections.sort() methods, which are:

有两个重载的Collections.sort()方法,它们是:

  1. sort(List list): Sorts the elements of the List in ascending order of their natural ordering.

    sort(List list) :以自然顺序的升序对List的元素进行排序。
  2. sort(List list, Comparator c): Sorts the elements of the list according to the order induced by the comparator.

    sort(List list, Comparator c) :根据比较器引发的顺序对列表中的元素进行排序。

Note that the above methods signature use generics but I have removed them here for simplicity in reading. Let us one by one dig into how and when we can use both these methods.

请注意,上述方法签名使用了泛型,但为了简化阅读,此处已将其删除。 让我们一步一步地探讨如何以及何时使用这两种方法。

Java Collections排序(列表) (Java Collections sort(List list))

Consider an ArrayList of String:

考虑一个StringArrayList

List<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Grape");

Now, we will sort it using Collections.sort():

现在,我们将使用Collections.sort()对它进行排序:

Collections.sort(fruits);
// Print the sorted list
System.out.println(fruits);

The output of this program will be:

该程序的输出为:

[Apple, Banana, Grape, Orange]

Hence, we can see that Collections.sort() has sorted the list of String in Lexical order. And it does not return anything.

因此,我们可以看到Collections.sort()以Lexical顺序对String列表进行了排序。 它不返回任何东西。

What if we have a list of custom objects? Of course, we can sort them as well.
Consider a class Fruit:

如果我们有一个自定义对象列表怎么办? 当然,我们也可以对它们进行排序。
考虑一类水果:

package com.journaldev.collections;
public class Fruit{
    private int id;
    private String name;
    private String taste;

    Fruit(int id, String name, String taste){
        this.id=id;
        this.name=name;
        this.taste=taste;
    }
}

Let’s create a list of Fruits:

让我们创建一个水果列表:

List<Fruit> fruitList=new ArrayList<Fruit>();
Fruit apple=new Fruit(1, "Apple", "Sweet");
Fruit orange=new Fruit(2, "Orange", "Sour");
Fruit banana=new Fruit(4, "Banana", "Sweet");
Fruit grape=new Fruit(3, "Grape", "Sweet and Sour");

fruitList.add(apple);
fruitList.add(orange);
fruitList.add(banana);
fruitList.add(grape);

In order to sort this list, if we directly use the Collections.sort(List list), it will give a Compile Time Error because there is no natural ordering defined for the Fruit objects. So, it doesn’t know how to sort this list.

为了对该列表进行排序,如果我们直接使用Collections.sort(List list) ,则会出现“编译时错误”,因为没有为Fruit对象定义自然顺序。 因此,它不知道如何对该列表进行排序。

For objects to have a natural order they must implement the interface java.lang.Comparable.

为了使对象具有自然顺序,它们必须实现接口java.lang.Comparable

The Comparable interface has a method compareTo(), which returns a negative, 0, a positive if the current value is less than, equal to, or greater than the value we are comparing with, respectively.

Comparable接口具有compareTo()方法,如果当前值分别小于,等于或大于我们要与之比较的值,则该方法将返回负数,0和正数。

Let’s enhance the Fruit class to implement Comparable interface. We are defining that the natural order of sorting is based on the “id” field of Fruit:

让我们增强Fruit类以实现Comparable 接口 。 我们定义自然排序的顺序是基于Fruit的“ id”字段:

package com.journaldev.collections;
public class Fruit implements Comparable<Object>{
    private int id;
    private String name;
    private String taste;

    Fruit(int id, String name, String taste){
        this.id=id;
        this.name=name;
        this.taste=taste;
    }
    @Override 
    public int compareTo(Object o) {
        Fruit f = (Fruit) o; 
        return this.id - f.id ;
    }
}

Now that we have implemented Comparable, we can sort the list without any errors:

现在我们已经实现了Comparable ,我们可以对列表进行排序而不会出现任何错误:

Collections.sort(fruitList);
fruitList.forEach(fruit -> {
    System.out.println(fruit.getId() + " " + fruit.getName() + " " + 
      fruit.getTaste());
});

The output will be as below:

输出将如下所示:

1 Apple Sweet
2 Orange Sour
3 Grape Sweet and Sour
4 Banana Sweet

Java集合排序(列表列表,比较器c) (Java Collections sort(List list, Comparator c))

In order to define a custom logic for sorting, which is different from the natural ordering of the elements, we can implement the java.util.Comparator interface and pass an instance of it as the second argument of sort().

为了定义不同于元素自然排序的自定义逻辑,我们可以实现java.util.Comparator接口,并将其实例作为sort()的第二个参数传递。

Let’s consider that we want to define the ordering based on the “name” field of the Fruit. We implement the Comparator, and in its compare() method, we need to write the logic for comparison:

让我们考虑我们要基于Fruit的“名称”字段定义排序。 我们实现了Comparator ,并在其compare()方法中,需要编写用于比较的逻辑:

package com.journaldev.collections;

class SortByName implements Comparator<Fruit> {
    @Override
    public int compare(Fruit a, Fruit b) {
        return a.getName().compareTo(b.getName());
    }
}

Now, we can sort it using this comparator:

现在,我们可以使用以下比较器对其进行排序:

Collections.sort(fruitList, new SortByName());

The output will be as below:

输出将如下所示:

1 Apple Sweet
4 Banana Sweet
3 Grape Sweet and Sour
2 Orange Sour

Instead of writing new class for Comparator, using lambda function, we can provide sorting logic at runtime as well:

除了使用lambda函数编写新的Comparator类外,我们还可以在运行时提供排序逻辑:

Collections.sort(fruitList, (a, b) -> {
    return a.getName().compareTo(b.getName());
});

Java Collections.reverseOrder (Java Collections.reverseOrder)

By default, Collection.sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods:

默认情况下, Collection.sort以升序执行排序。 如果我们想以相反的顺序对元素进行排序,则可以使用以下方法:

  1. reverseOrder(): Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.

    reverseOrder() :返回一个Comparator ,它强加集合元素的自然顺序。
  2. reverseOrder(Comparator cmp): Returns a Comparator that imposes reverse ordering of the specified comparator.

    reverseOrder(Comparator cmp)返回一个Comparator指定的比较的强加反向排序。

Here are the examples for both these methods:

这是这两种方法的示例:

Java Collections reverseOrder()示例 (Java Collections reverseOrder() example)

Collections.sort(fruits, Collections.reverseOrder());
System.out.println(fruits);

It’ll output the fruits in reverse alphabetical order:

它将以相反的字母顺序输出水果:

[Orange, Grape, Banana, Apple]

Java Collections reverseOrder(Comparator cmp)示例 (Java Collections reverseOrder(Comparator cmp) example)

Collections.sort(fruitList, Collections.reverseOrder(new SortByName()));
fruitList.forEach(fruit -> {
    System.out.println(fruit.getId() + " " + fruit.getName() + " " + 
      fruit.getTaste());
});

Output:

输出:

2 Orange Sour
3 Grape Sweet and Sour
4 Banana Sweet
1 Apple Sweet

That’s all for Java Collections sort() method and it’s examples.

这就是Java Collections sort()方法及其示例的全部内容。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16094/java-collections-sort

 类似资料: