Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the expression based on Arrays.sort () and lambda

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you based on Arrays.sort () and lambda expression how to achieve, I believe that most people do not understand, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

Arrays.sort () and lambda expressions 1. Sort the array of basic data types

Numerical sort:

Int [] intArray = new int [] {1 Arrays.sort (intArray); System.out.println (Arrays.toString (intArray))

String sorting (uppercase followed by lowercase):

String [] strArray = new String [] {"Z", "a", "D"}; Arrays.sort (strArray); System.out.println (Arrays.toString (strArray))

String sorting (ignore case):

Arrays.sort (strArray, String.CASE_INSENSITIVE_ORDER)

Reverse sort:

Arrays.sort (strArray, Collections.reverseOrder ())

Note: Arrays.sort () uses a two-axis fast row:

1. For very small arrays (less than 27 in length), insert sorting is used.

two。 Select two points, P1 and P2, as the pivot. For example, we can use the first element and the last element.

3.P1 must be smaller than P2, otherwise the two elements will be swapped, and the entire array will now be divided into four parts:

(1) part I: elements smaller than P1.

(2) part II: elements larger than P1 but smaller than P2.

(3) the third part: elements larger than P2.

(4) part IV: parts that have not yet been compared.

Before starting the comparison, except for the pivot point, almost all the other elements are in the fourth part, until after the comparison, there are no elements in the fourth part.

4. Select an element a [K] from the fourth part, compare it with the two axes, and put it into one of the 123rd parts.

5. Move LMagol KMAG to point to.

6. Repeat 4 or 5 steps until there are no elements in the fourth part.

7. Swap P1 with the last element of the first part. Swap P2 with the first element of part 3.

8. Sort the first, second and third parts recursively.

For arrays of basic types such as int [], double [], char [], the Arrays class only provides the default ascending order, not descending order, so you need to pass in a custom comparator and, using Arrays.sort (num,c), pass in an object c of the class that implements the Comparator interface. To arrange in reverse order:

Arrays.sort (num,new Comparator () {public int compare (Integer a, Integer b) {return bmura;}})

Other methods of Arrays:

Arrays.sort (num, fromIndex, toIndex); sort an interval.

Arrays.sort (num, fromIndex, toIndex,c); sort an interval by c comparator.

2. Sort the array of objects

The Comparable interface or Comparator interface is required first.

Comparison of the two comparators:

Internal comparator: the object to be compared must implement the Comparable interface and override the compareTo (To) method to indicate that the object can be used for sorting, otherwise the Arrays.sort () method cannot be used directly.

Public class Employee implements Comparable {private int id;// employee number private double salary;// employee salary public int getId () {return id;} public void setId (int id) {this.id = id;} public double getSalary () {return salary } public void setSalary (double salary) {this.salary = salary;} public Employee (int id, double salary) {super (); this.id = id; this.salary = salary } / / for output convenience, rewrite the toString method @ Override public String toString () {/ / simple output information return "id:" + id + ", salary=" + salary " } / / compare the order of this object with the specified object @ Override public int compareTo (Employee o) {/ / compare the employee number. If the number of this object is greater than, equal to, or less than the specified object, 1, 0,-1 int result = this.id > o.id? 1: (this.id = = o.id? 0:-1) / / if the number is equal, compare salary if (result = = 0) {/ / compare employee salary. If the salary of this object is greater than, equal to, or less than the specified object, return 1, 0,-1 result = this.salary > o.salary? 1: (this.salary = = o.salary? 0:-1);} return result }}

External comparator: you need to write a comparator to implement the Comparator interface, and implement the compare (T1, T2) method, and define the comparison rules according to your own requirements. It is more flexible to use an external comparator, for example, the requirement is now sorted by employee number and salary, and it may be sorted by name later, so just write a comparator that is compared according to the name rule.

/ * Test two comparators * @ author Sam * * / public class TestEmployeeCompare {/ * * @ param args * / public static void main (String [] args) {List employees = new ArrayList (); employees.add (new Employee (2, 5000)); employees.add (new Employee (1, 4500)) Employees.add (new Employee (4, 3500)); employees.add (new Employee (5, 3000)); employees.add (new Employee (4, 4000)); / / Internal comparator: the object to be sorted requires to implement the Comparable interface, which can be passed directly to the object Arrays.sort (employees); System.out.println ("implemented through internal comparator:") System.out.println (employees); List employees2 = new ArrayList (); employees2.add (new Employee (2, 5000)); employees2.add (new Employee (1, 4500)); employees2.add (new Employee (4, 3500)); employees2.add (new Employee (5, 3000)); employees2.add (new Employee (4, 4000)) / / external comparator: custom class implements Comparator interface, which requires passing custom comparator class Arrays.sort (employees2, new EmployeeComparable ()); System.out.println ("implemented through external comparator:"); System.out.println (employees2) }} / * Custom employee comparator * / class EmployeeComparable implements Comparator {@ Override public int compare (Employee o1, Employee O2) {/ / compare employee numbers if the number of this object is greater than, equal to, or less than the specified object Return 1, 0,-1 int result = o1.getId () > o2.getId ()? 1: (o1.getId () = = o2.getId ()? 0:-1) / / if the number is equal, compare salary if (result = = 0) {/ / compare employee salary. If the salary of this object is greater than, equal to, or less than the specified object, return 1, 0,-1 result = o1.getSalary () > o2.getSalary ()? 1: (o1.getSalary () = = o2.getSalary ()? 0:-1) } return result;}}

Finally, skillfully use the lambda expression: (parameter)-> an expression or a piece of code

Such as:

Achieve reverse order:

Arrays.sort (nums, (Integer a, Integer b)-> {return bmura;})

Array of strings, sorted by length:

Arrays.sort (strs, (String first, String second)-> {if (first.length ())

< second.length()) return -1; else if(first.length() >

Second.length () return 1; else return 0;}); discuss Comparator- using lambda expression again

First write a Person class, which mainly has two member properties, address and name, and their getter () method, and finally complement and override the toString () method.

Public class Person {private String address; private String name; public Person (String firstName, String lastName) {this.address = firstName; this.name = lastName;} public String getAddress () {return address;} public String getName () {return name } @ Override public String toString () {return getClass () .getSimpleName () + "{" + "address='" + address +'\'+ ", name='" + name +'\'+'}';}} before

In the past, when you wrote a comparison sort, you always had to write a lot of code, such as the following:

Public class TestCh06 {public static void main (String... Args) throws CloneNotSupportedException {/ / defines an array of Person classes Person [] arr = {new Person ("wo", "2722"), new Person ("uj", "2829"), new Person ("dh", "2829"), new Person ("us", "1"), new Person ("jaka", "881711")}; LenComparator lc = new LenComparator () / sort Arrays.sort (arr, lc); System.out.println (Arrays.toString (arr));}} / * comparator sorted by name length-> arrays of type String * / class LenComparator implements Comparator {@ Override public int compare (Person o1, Person O2) {return Integer.compare (o1.getName (). Length (), o2.getName (). Length ()) }} now

Now that Java8SE has been out for a long time, it is a bit less elegant to write with the above code, because the Comparator interface contains many convenient static method class creation comparators (these methods can be used for lambda expressions or method references).

/ / sort by name Arrays.sort (arr,Comparator.comparing (Person::getName)); / / sort by name length Arrays.sort (arr,Comparator.comparing (Person::getName, (sdint)-> Integer.compare (s.length (), t.length (); Arrays.sort (arr,Comparator.comparingInt (p-> p.getName (). Length () / / sort by name first, and then compare Arrays.sort (arr,Comparator.comparing (Person::getName) .thencomparing (Person::getAddress)) by address if the name is the same. This is all the content of the article "how to implement expressions based on Arrays.sort () and lambda". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report