Sorting Java Collections

Source: Internet
Author: User
Tags comparable set set sorts

In actual development, we often need to sort the entities in an entity collection according to one of the entity's fields, and then display them in an orderly manner to the interface. For example: We get a student collection, and the requirements require that we can sort by the student's name or the student's score.

The collection of entities we get is generally a list or set type, so here's an introduction to the sort of both.


1. List sort

The list collection itself is ordered, so it's easier to sort it, which is divided into two categories based on the type of the list collection element:

1.1 When the set elements can be sorted naturally  

The so-called "natural sort" refers to the type of elements in the list collection that implements the Comparable<t> interface, such as the string type and the integer type:


  


The list ordering for this type is simple, just call collections.sort (list<t>list) to sort the list in the parameter, as shown in the following example:

public class Testlistsort {@SuppressWarnings ("unchecked") public static void Main (string[] argstrings) {ArrayList Strlist = new ArrayList (); ArrayList intlist = new ArrayList () Strlist.add ("B"); Strlist.add ("a"); Strlist.add ("C"); Intlist.add (2); Intlist.add ( 1); Intlist.add (3);p rint (intlist);//1.0, sort "front" output: 2 1 3print (strlist);//1.1, sort "front" output: B a Ccollections.sort (intlist); Collections.sort (strlist);p rint (intlist);//2.0, sort "after" output: 1 2 3print (strlist);//2.1, sort "after" output: a b c}public static void Print (list list) {for (int i = 0; i < list.size (); i++) {System.out.println (List.get (i))}}}

1.2 When the set element "not" can be sorted naturally  

That is, the type of the element in the list collection "does not" implement the Comparable<t> interface, for example, a custom Class (Student). You need to sort by using collections.sort (List<t>list, comparator< super t> C) , the core of which is the second parameter, which is to customize a collation. Examples are as follows:

1, the following we first customize a student Class (Student):

public class Student {private String stuname;private int score;//------get/setpublic String getstuname () {return stuname; }public void Setstuname (String stuname) {this.stuname = Stuname;} public int Getscore () {return score;} public void SetScore (int score) {This.score = score;}}

2. Then constructs an object of type list<student>, and the printing method

public static list<student> getliststudents () {list<student> liststudents = new Arraylist<student> () ; Student STU2 = new Student () stu2.setstuname ("Stu2"); Stu2.setscore (70); Student stu1 = new Student () stu1.setstuname ("stu1"); Stu1.setscore (50); Student stu3 = new Student () stu3.setstuname ("Stu3"); Stu3.setscore (Liststudents.add); STU2 Liststudents.add ( STU1); Liststudents.add (STU3); return liststudents;} public static void Printstulistname (List<student> List) {for (int i = 0; i < list.size (); i++) {System.out.printl N (List.get (i). Getstuname ());}}

3. Then the test sorts the list<student> by "name"

public static void Main (string[] args) {list<student> liststudents = getliststudents ();p rintstulistname ( liststudents);//1, sort "front" output: Stu2 stu1 stu3System.out.println ("----------------------------------------");//Custom collation , sorted by student's "name" Collections.sort (liststudents, New comparator<student> () {@Overridepublic int compare (Student STU1, Student stu2) {return stu1.getstuname (). CompareTo (Stu2.getstuname ());//Sort By "name"//Return Stu1.getscore () > Stu2.getscore ()? 1: -1;//According to "Age"});p Rintstulistname (liststudents);//2, sorted by "name" Output: STU1 stu2 Stu3}

2, TreeSet sort

In a real project, when there is a one-to-many or many-to-many relationship in an entity association, many of the parties are generally represented by a set set (HashSet), so we often need to sort by a field in the set collection when we get to an entity collection to return to the interface. Entity Association General with HashSet, but we know that HashSet itself is disorderly, but treeset is orderly, so hashset sort of a thought is first to TreeSet reorder, hashset sort of several ideas will be introduced in the following. The sorting of TreeSet is described below.

2.1 Sorting Principle  

The sort of treeset is actually the same as the list sort principle above, and the difference is that when TreeSet puts the (add) element, the sorting method (CompareTo ()) is automatically called by the sort (if the collection element is natural) to sort the elements in the collection. Instead of manually calling a sorting method. Examples are as follows:

public class Testtreesetsort {@SuppressWarnings ("unchecked") public static void main (string[] args) {TreeSet TreeSet = new TreeSet ();//The trace source will find that when the TreeSet Add method is executed, the elements inside are automatically sorted treeset.add ("a"); Treeset.add ("C"); Treeset.add ("B"); Iterator Treesetiterator = Treeset.iterator ();//Loop output TreeSet content: a b cwhile (Treesetiterator.hasnext ()) {System.out.println ( Treesetiterator.next ());}}}

The following is a student (same as 1.2 in the student Class) of the order of the TreeSet set of thinking analysis, there are generally two ways :


2.2 using the TreeSet default ordering, the collection element implements the comparable interface  

That is, using the default sorting principle of the above TreeSet, student objects are automatically sorted when they are placed in the TreeSet collection.

Of course, the immutable student class is not automatically sorted, to enjoy this service, you need to transform this student, let it implement comparable interface, and rewrite the CompareTo () method, we can customize the collation in the method, the code is as follows:


2.2.1, modified Student class

public class Student implements comparable {private String stuname;private int score;//When executing treeset<student> 's add () The method is automatically called when the method is ordered @overridepublic int compareTo (Object obj) {Student stu = (Student) Obj;return This.stuName.compareTo ( Stu.getstuname ());} ------get/setpublic String Getstuname () {return stuname;} public void Setstuname (String stuname) {this.stuname = Stuname;} public int Getscore () {return score;} public void SetScore (int score) {This.score = score;}}

2.2.2, and then constructs an object of type treeset<student>, and the printing method

public static treeset<student> gettreesetstudents () {treeset<student> treesetstudents = new TreeSet< Student> (); Student STU2 = new Student () stu2.setstuname ("Stu2"); Stu2.setscore (70); Student stu1 = new Student () stu1.setstuname ("stu1"); Stu1.setscore (50); Student stu3 = new Student () stu3.setstuname ("Stu3"); Stu3.setscore (90);//The Student class CompareTo () is automatically called when the Add method is executed method to sort Treesetstudents.add (STU2); Treesetstudents.add (STU1); Treesetstudents.add (STU3); return treesetstudents;} public static void Printstutreesetname (Treeset<student> treesetstudents) {for (Student student:treesetstudents) {System.out.println (Student.getstuname ());}}

  2.2.3.then test the output constructed Treeset<student> object to see if it has been sorted

public static void Main (string[] args) {treeset<student> treesetstudents = Gettreesetstudents (); Printstutreesetname (treesetstudents);//output is ordered: STU1 stu2 STU3}

2.3 Sorting by TreeSet (comparator<? Super E>comparator) method  

That is, the manual construction of the comparator treeset, the form is different, in fact, the principle is the same, the code is as follows:


2.3.1, also with the original Student Class (Student):

public class Student {private String stuname;private int score;//------get/setpublic String getstuname () {return stuname; }public void Setstuname (String stuname) {this.stuname = Stuname;} public int Getscore () {return score;} public void SetScore (int score) {This.score = score;}}

  2.3.2, then customize a sort (Compare) class

/** * @author Wangzhipeng *  */public class Mycomparator implements Comparator {@Overridepublic int compare (Object elem Ent1, Object element2) {Student stu1 = (Student) element1; Student STU2 = (Student) element2;int result = Stu1.getstuname (). CompareTo (Stu2.getstuname ()); return result;}}

  2.3.3.then constructs an object of type treeset<student> "to pass in an object of the above mycomparator as a parameter", and the printing method

public static treeset<student> gettreesetstudents () {//key point, New one Treeset<student> object, Pass the object of the custom sort class we have written as a parameter into the treeset<student> treesetstudents = new treeset<student> (new Mycomparator ()); Student STU2 = new Student () stu2.setstuname ("Stu2"); Stu2.setscore (70); Student stu1 = new Student () stu1.setstuname ("stu1"); Stu1.setscore (50); Student stu3 = new Student () stu3.setstuname ("Stu3"); Stu3.setscore (90);//The Mycomparator class compare is automatically called when the Add method is executed ( Object element1, object//element2) method to sort Treesetstudents.add (STU2); Treesetstudents.add (STU1); Treesetstudents.add ( STU3); return treesetstudents;} public static void Printstutreesetname (Treeset<student> treesetstudents) {for (Student student:treesetstudents) {System.out.println (Student.getstuname ());}}

  2.3.4.then test the output constructed Treeset<student> object to see if it has been sorted

public static void Main (string[] args) {treeset<student> treesetstudents = Gettreesetstudents (); Printstutreesetname (treesetstudents);//output is ordered: STU1 stu2 STU3}

3, HashSet sort

I also mentioned above that the entity-related parties are generally expressed in unordered hashset, rather than in an orderly treeset. So we introduce the hashset of the order of thought.

The idea is very simple, hashset is unordered, itself certainly does not have the function of sorting, so want to sort it to turn it to the above two ordered set list or TreeSet, the code is as follows:


3.1. First obtain an object of type hashset<student>

public static hashset<student> gethashsetstudents () {hashset<student> hashsetstudents = new HashSet< Student> (); Student STU2 = new Student () stu2.setstuname ("Stu2"); Stu2.setscore (70); Student stu1 = new Student () stu1.setstuname ("stu1"); Stu1.setscore (50); Student stu3 = new Student () stu3.setstuname ("Stu3"); Stu3.setscore (90);//The Student class CompareTo () is automatically called when the Add method is executed method to sort Hashsetstudents.add (STU2); Hashsetstudents.add (STU1); Hashsetstudents.add (STU3); return hashsetstudents;}

  3.2, sort this object

public static void Main (string[] args) {//Get a Hashset<student> object hashset<student> hashsetstudents = Gethashsetstudents ();//1. Convert the above object to a List<student> object and sort list<student> liststudents = new arraylist< Student> (hashsetstudents); Collections.sort (liststudents, New comparator<student> () {@Overridepublic int compare (Student stu1, Student stu2 {return Stu1.getstuname (). CompareTo (Stu2.getstuname ());//Sort by "name"}});//loop out the ordered elements: stu1 stu2 stu3for (Student student:liststudents) {System.out.println (Student.getstuname ());} 2. Convert the above object to a Treeset<student> object treeset<student> treesetstudents = new Treeset<student> (new Mycomparator ()); for (Student student:hashsetstudents) {treesetstudents.add (Student);} Cyclic output of sequenced elements: STU1 stu2 stu3for (Student student:treesetstudents) {System.out.println (Student.getstuname ());}}

4. Summary

These sorts of collections seem to have many kinds of ways, in fact, the bottom-level implementation can be categorized into one, whether it is called the default sorting method of the collection or custom sorting, in fact, it can be said to be a compare (Object o1,object O2) method.

Sorting Java Collections

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.