Java. util. List multi-field sorting

Source: Internet
Author: User

You can useJava. util. Collections. Sort (list <t>, comparator <? Super T>)This is an easy-to-use method. However, it is often seen that someone is asking how to sort multiple fields of an element. This question is like an SQL statement'Order'Sentence, followed by several sorting conditions.

For example, for sorting element FOO:

Class Foo {

Int;

Int B;

}

Foo. A is the first sorting field, and foo. B is the second sorting field, that is, the foo. B is determined under the condition of two Foo such as Foo.. Then our comparator can perform the following operations:

Collections. sort (l, new Comparator <Foo> () {<br/> @ Override <br/> public int compare (Foo f1, Foo f2) {<br/> if (f1.a-f2.a> 0) {<br/> return 1; <br/>} else if (f1.a-f2.a <0) {<br/> return-1; <br/>} else {// Foo. a equal, then check Foo. B <br/> return f1. B-f2. B; <br/>}< br/> }});

 

Or you can use a method that is more common than others:

/** <Br/> * Sort <code> List </code> by multiple conditions. <br> <br/> * It's like SQL 'ORDER BY' clause. input multiple <code> Comparator </code> <br/> * in List as argument. <br/> * @ param <T> <br/> * @ param list <br/> * @ param comparatorList <br/> * @ throws IllegalArgumentException if comparatorList is empty <br/> * @ author shengyuan. lu Shengyuan <michaellufhl@yahoo.com.cn> <br/> */<br/> public static <T> void sort (List <T> list, final List <Comparator <T> comparatorList) {<br/> if (comparatorList. isEmpty () {// Always equals, if no Comparator. <br/> throw new IllegalArgumentException ("comparatorList is empty. "); <br/>}< br/> Comparator <T> comparator = new Comparator <T> () {<br/> public int compare (T o1, T o2) {<br/> for (Comparator <T> c: comparatorList) {<br/> if (c. compare (o1, o2)> 0) {<br/> return 1; <br/>} else if (c. compare (o1, o2) <0) {<br/> return-1; <br/>}< br/> return 0; <br/>}< br/>}; <br/> Collections. sort (list, comparator); <br/>}

The most efficient way is to combine each sorted comparator into a comparator and then sort it.

 

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.