java arraylist sort,Java集合sort()

 2023-11-19 阅读 22 评论 0

摘要: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時 ,我們比以往更需要對數據進行排序。 J

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實現(如LinkedList和ArrayList Collections.sort()進行排序。

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

java arraylist sort。 有兩個重載的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():

Java applet、 現在,我們將使用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:

java集合sort、 如果我們有一個自定義對象列表怎么辦? 當然,我們也可以對它們進行排序。
考慮一類水果:

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 list.sort、 為了使對象具有自然順序,它們必須實現接口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:

sort java, 現在我們已經實現了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:

javasort的用法, 讓我們考慮我們要基于Fruit的“名稱”字段定義排序。 我們實現了Comparator ,并在其compare()方法中,需要編寫用于比較的邏輯:

package com.journaldev.collections;class SortByName implements Comparator<Fruit> {@Overridepublic 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:

java排序sort? 除了使用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:

Java list排序、 它將以相反的字母順序輸出水果:

[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

java集合排序sort。 參考: API文檔

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/183228.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息