In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the three implementation methods of List sorting in Java? many beginners are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
Preface
In some special scenarios, we need to sort the List collection in the Java program. For example, get the list of all users from the third-party interface, but the list is sorted by user number from small to large by default, and our system needs to sort according to the user's age from big to small. At this time, we need to customize the sorting operation on the List collection.
There are three common ways to sort List:
Sort using Comparable
Sort using Comparator
If it is an environment above JDK 8, you can also use the Stream stream for sorting.
Let's take a look at the specific implementation of various sorting methods.
1. Sort using Comparable
According to the scenario designed in this article, we need to create a List collection containing a list of users, and sort them according to the age of the users. The specific implementation code is as follows:
Public class ListSortExample {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (1,30, "Beijing")); add (new Person (2,20, "Xi'an")); add (new Person (3,40, "Shanghai"));}} / / use the rules defined by Comparable to sort Collections.sort (list); / / print the list collection list.forEach (p-> {System.out.println (p);});}} / / the following set/get/toString uses lombok's annotation @ Getter@Setter@ToStringclass Person implements Comparable {private int id; private int age; private String name Public Person (int id, int age, String name) {this.id = id; this.age = age; this.name = name;} @ Override public int compareTo (Person p) {return p.getAge ()-this.getAge ();}}
The execution result of the above code is shown in the following figure:
The core code of this method is as follows:
two。 Sort using Comparator
Comparable is the comparison method within the class, while Comparator is the comparator outside the sort class. Using the Comparator comparator, you do not need to modify the original Person class, you only need to extend a comparator of the Person class. There are two ways to implement Comparator:
Create a new Comparator comparator
Use the Comparator anonymous class comparator.
Among them, the second implementation method is more concise, let's observe the difference between the two through the following specific code.
2.1 New Comparator comparator public class ListSortExample2 {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (1,30, "Beijing")); add (new Person (2,20, "Xi'an")); add (new Person (3,40, "Shanghai"));}} / use Comparator comparator to sort Collections.sort (list, new PersonComparator ()); / / print list collection list.forEach (p-> {System.out.println (p);}) }} / * New Person comparator * / class PersonComparator implements Comparator {@ Override public int compare (Person p1, Person p2) {return p2.getAge ()-p1.getAge ();} @ Getter@Setter@ToStringclass Person {private int id; private int age; private String name; public Person (int id, int age, String name) {this.id = id; this.age = age This.name = name;}}
The execution result of the above code is shown in the following figure:
The core implementation code of this method is as follows:
2.2 Anonymous Class comparator
The comparator Comparator can use a more concise anonymous class to implement the sorting function, as shown in the following code:
Public class ListSortExample2 {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (1,30, "Beijing")); add (new Person (2,20, "Xi'an")); add (new Person (3,40, "Shanghai"));}} / use anonymous comparator to sort Collections.sort (list, new Comparator () {@ Override public int compare (Person p1, Person p2) {return p2.getAge ()-p1.getAge ();}}); / / print list collection list.forEach (p-> {System.out.println (p)) @ Getter@Setter@ToStringclass Person {private int id; private int age; private String name; public Person (int id, int age, String name) {this.id = id; this.age = age; this.name = name;}}
The execution result of the above code is shown in the following figure:
3. Sort using Stream stream
After JDK 8, you can use a simpler method, Stream stream, to implement sorting, which requires only one line of code, as follows:
Public class ListSortExample3 {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (1,30, "Beijing")); add (new Person (2,20, "Xi'an")); add (new Person (3,40, "Shanghai"));}} / sort list = list.stream () .sorted (Comparator.comparing (Person::getAge). Reversed ()) .ordering (Collectors.toList ()) using Stream; / / print the list collection list.forEach (p-> {System.out.println (p);});} @ Getter @ Setter @ ToString static class Person {private int id Private int age; private String name; public Person (int id, int age, String name) {this.id = id; this.age = age; this.name = name;}
Where reversed () means reverse order, and if you don't use this method, it's positive order.
The execution result of the above code is shown in the following figure:
Extension: sort field is null
When sorting with Stream, an exception occurs if there is a null value in the sorted field. The specific example is as follows:
Public class ListSortExample4 {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (30, "Beijing")); add (new Person (10, "Xi'an"); add (new Person (40, "Shanghai")); add (new Person (null, "Shanghai")) / / null value}}; / / in the positive order of [age], but there is a null value list = list.stream (). Sorted (Comparator.comparing (Person::getAge)) .ages (Collectors.toList ()); / / print the list collection list.forEach (p-> {System.out.println (p);}) @ Getter@Setter@ToStringclass Person {private Integer age; private String name; public Person (Integer age, String name) {this.age = age; this.name = name;}}
The execution result of the above code is shown in the following figure:
To solve the above problem, you need to pass the second parameter to Comparator.comparing: Comparator.nullsXXX, as shown in the following code:
Public class ListSortExample4 {public static void main (String [] args) {/ / create and initialize List List list = new ArrayList () {{add (new Person (30, "Beijing")); add (new Person (10, "Xi'an"); add (new Person (40, "Shanghai")); add (new Person (null, "Shanghai")) }}; / / in the positive order of [age], but there is a null value in the age list = list.stream (). Sorted (Comparator.comparing (Person::getAge, Comparator.nullsFirst (Integer::compareTo) .Collectors.toList (Collectors.toList ()); / / print the list collection list.forEach (p-> {System.out.println (p)) }); @ Getter@Setter@ToStringclass Person {private Integer age; private String name; public Person (Integer age, String name) {this.age = age; this.name = name;}}
Comparator.nullsFirst means to put the null value in the sort field at the front of the collection, and you can use Comparator.nullsLast if you want to put the null value at the end of the collection.
The execution result of the above code is shown in the following figure:
Three List sorting methods are described above. The first two methods are often used in versions before JDK 8, in which the comparator Comparator is written in two ways, while in the version after JDK 8, you can use Comparator.comparing to sort. If a null value may appear in the sorting field, use Comparator.nullsXXX for sorting processing (otherwise an error will be reported).
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.