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:

有两个重载的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> {@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:

除了使用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

Java集合sort()相关推荐

  1. java集合sort底层实现_Java面试总结系列之Collections.sort()

    面试中被问到,集合类中的排序方法是怎么实现的?没有回答上来,故而总结如下:你知道么? 前提:在eclipse中对于自己的代码可以通过按住Ctrl的同时单击名称跳入相应源码中.但eclipse默认没有添 ...

  2. 终于,我读懂了所有Java集合——sort

    Collections.sort 事实上Collections.sort方法底层就是调用的Arrays.sort方法,而Arrays.sort使用了两种排序方法,快速排序和优化的归并排序. 快速排序主 ...

  3. java集合总结_Java中集合总结

    Java数组的长度是固定的,为了使程序能够方便地存储和操作数目不固定的一组数据,JDK类库提供了Java集合,这些集合类都位于java.util包中,但是与数组不同的是,集合中不能存放基本类型数据,而 ...

  4. Java集合框架综述,这篇让你吃透!

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:平凡希 cnblogs.com/xiaoxi/p/60899 ...

  5. 【Java集合框架】ArrayList类方法简明解析(举例说明)

    本文目录 1.API与Java集合框架 2.ArrayList类方法解析 2.1 add() 2.2 addAll() 2.3 clear() 2.4 clone() 2.5 contains() 2 ...

  6. Java基础篇:Java集合

    文章目录 1.概述 2.Collection接口 2.1 Collection接口方法 2.2 Iterator迭代器接口 2.3 Collection子接口之:List接口 2.4 Collecti ...

  7. java集合框架综述

    一.集合框架图 简化图: 说明:对于以上的框架图有如下几点说明 1.所有集合类都位于java.util包下.Java的集合类主要由两个接口派生而出:Collection和Map,Collection和 ...

  8. java集合代码_Java-集合(示例代码)

    一.Java集合框架概述 ●一方面,面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就要对对象进行存储.另一方面,使用Array存储对象方面具有一些弊端,而Java集合就像一种容器 ...

  9. java集合框架图(一)

    一.集合类简介 Java集合就像一种容器,可以把多个对象(实际上是对象的引用,但习惯上都称对象)"丢进"该容器中.从Java 5 增加了泛型以后,Java集合可以记住容器中对象的数 ...

最新文章

  1. Sass (Syntactically Awesome StyleSheets)
  2. 让Maven项目使用Nexus作为远程仓库的settings.xml配置
  3. find中的-print0和xargs中-0的奥妙
  4. AFNetworking 2.0使用(持续更新)
  5. php编码和c语言,急求windows下用c语言开发PHP扩展时,在C语言里把字符串转成utf-8编码再打印的方法。...
  6. 华三交换机mode是什么意思_POE交换机150米、长距离250米传输是什么意思?
  7. Microsoft.NET框架程序设计--18 异常
  8. CodeBlocks调试功能(转)
  9. 还不会财务管理分析?Python爬取全网财务分析数据
  10. C/C++编程:#pragma once用法总结
  11. python 图片合并pdf_利用python将多张图片合并为pdf文档
  12. Win11更新或更改时间后闪白屏的解决方法
  13. 3d学习笔记(十)——多人联机游戏
  14. 家居收纳打造一个美好的家-央央家政家居收纳
  15. 【数据库】ER图进行描述某系统之学习七
  16. 计算机小白如何真正入门计算机?
  17. 图片转成pdf格式怎么转?
  18. 这是请程序员设计的楼梯吧
  19. Windows 8寄托着微软对移动计算、客厅控制和超级操作系统的全新理解与尝试
  20. hiper – web_Web设计行业分析–专业人士与业余者[信息图]

热门文章

  1. 整合TextBox与Label 创建新控件--EFLabelText
  2. 深入ASP.NET 2.0的提供者模型
  3. 毕业2月有余,苏州同学腐败第二次大聚会
  4. [转载] OpenCV—Python目标区域图像分割
  5. 转:超级好用的流程图js框架
  6. javaEE插件安装
  7. 关键字:auto、static、register、const、volatile 、extern 总结
  8. 当卷积层后跟batch normalization层时为什么不要偏置b
  9. 3.1 Tensorflow基础知识
  10. filemode对git diff的影响