java8--sorting sort

Source: Internet
Author: User

With the JAVA8, it is convenient to make the elements in the list in a positive sequence, flashback operation ~

    • Sort the numbers
// sort the numbers List<integer> nums = arrays.aslist (3,1,5,2,9,8,4,10,6,7);   // Reverseorder Reverse System.err.println ("reverse:" +nums); // Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1] Nums.sort (Comparator.naturalorder ()); // Naturalorder Natural sort i.e.: positive sequence SYSTEM.ERR.PRINTLN ("Positive order:" +nums); // positive Order: [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
    • Sort by an attribute of an object
 //Sort by an attribute of an object: for example, agelist<user> users =NewArraylist<>(); Users.add (NewUser ("U1", 22)); Users.add (NewUser ("U2", 18)); Users.add (NewUser ("U3", 35)); Users.add (NewUser ("U4", 16)); Users.add (NewUser ("U5", 40));/**
* O1,O2 indicates the object to be compared,
* Positive order: O1.getage (). CompareTo (O2.getage ())
* Reverse: O2.getage (). CompareTo (O1.getage ())
**/Users.sort ((O1, O2) o1.getage (). CompareTo (O2.getage ())); System.err.println ("Age Positive sequence:" +users);//Age sequence: [user{name= ' U4 ', age=16}, User{name= ' U2 ', age=18}, User{name= ' U1 ', age=22}, User{name= ' U3 ', age=35}, user{ Name= ' U5 ', age=40}]Users.sort (O1, O2) - o2.getage (). CompareTo (O1.getage ())); System.err.println ("Age Reverse:" +users);//Age Reverse: [user{name= ' U5 ', age=40}, User{name= ' U3 ', age=35}, User{name= ' U1 ', age=22}, User{name= ' U2 ', age=18}, user{ Name= ' U4 ', age=16}]

java8--sorting sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.