Java-collection framework Collections. sort (), Comparable interface, and Comparator interface, javasortcomparator

Source: Internet
Author: User
Tags comparable

Java-collection framework Collections. sort (), Comparable interface, and Comparator interface, javasortcomparator

  • Collentions tool class -- java. util. Collections

Collentions is a tool class used to operate collection objects in the Java Collection framework. It is also a member of the Java Collection framework and is in parallel with List, Map, and Set.

Collections. sort () sorting method to sort the elements in the List object.

Package com. test. collection; import java. util. arrayList; import java. util. collections; import java. util. list; import java. util. random; public class CollectionsTest {/*** sort Integer generic lists */public void testSort1 () {List <Integer> integerList = new ArrayList <Integer> (); // Insert 10 Random integers not repeated within 100, random Random = new Random (); Integer num; for (int I = 0; I <10; I ++) {do {num = random. nextInt (100);} while (integerList. contains (num); integerList. add (num); System. out. println ("successfully inserted INTEGER:" + num);} System. out. println ("=================== before sorting =================="); for (Integer integer: integerList) {System. out. print (integer + "");} // call Collections. the sort () method sorts Collections. sort (integerList); System. out. println ("=================== after sorting =================="); for (Integer integer: integerList) {System. out. print (integer + "") ;}/ *** String generic List for sorting
* String type comparison: numbers first, followed by letters, numbers 0-9, letters A-Za-z */public void testSort2 () {List <String> stringList = new ArrayList <String> (); // Add three unordered String elements, stringList. add ("google"); stringList. add ("lenovo"); stringList. add ("baidu"); System. out. println ("================== before sorting ===================="); for (String string String: stringList) {System. out. println (string);} Collections. sort (stringList); System. out. println ("=================== after sorting =================="); for (String string String: stringList) {System. out. println (string) ;}} public static void main (String [] args) {CollectionsTest ct = new CollectionsTest (); ct. testSort1 (); ct. testSort2 ();}}
  • Comparable interface and Comparator Interface

In Java, if two objects need to be sorted, they must be comparable. Comparable indicates that an object can be compared. Comparable defines default sorting rules for objects. If you use other rules to sort objects, you can use the Comparator interface to define temporary comparison rules. Both the Comparable interface and Comparator interface are members of the Java Collection framework.

Comparable interface:

Comparator interface:

Example: sort the Student Series by student id by default. Three integers less than 1000 are randomly generated as the student id, and then sorted by Student name.

Package com. test. collection; import java. util. arrayList; import java. util. collections; import java. util. list; import java. util. random; public class CollectionsTest {public void testSort () {List <Student> studentList = new ArrayList <Student> (); List <Integer> studentId = new ArrayList <Integer> (); random random = new Random (); Integer num; for (int I = 0; I <3; I ++) {do {num = random. nextInt (1000);} while (studentId. contains (num); studentId. add (num);} studentList. add (new Student (studentId. get (0) + "", "Tom"); studentList. add (new Student (studentId. get (1) + "", "Jack"); studentList. add (new Student (studentId. get (2) + "", "Xiaoming"); studentList. add (new Student (1000 + "", "Lily"); System. out. println ("============= before sorting =============="); for (Student student: studentList) {System. out. println ("student:" + student. id + "--" + student. name);} Collections. sort (studentList); System. out. println ("============= after sorting by id ================"); for (Student student: studentList) {System. out. println ("student:" + student. id + "--" + student. name);} System. out. println ("============= after sorting by name ========="); Collections. sort (studentList, new StudentComparator (); for (Student student: studentList) {System. out. println ("student:" + student. id + "--" + student. name) ;}} public static void main (String [] args) {CollectionsTest ct = new CollectionsTest (); ct. testSort ();}}

Execution result:

============= Before sorting ===================== Student: 118 -- Tom Student: 460 -- Jack Student: 51 -- Xiaoming students: 1000 -- Lily ============= sorted students: 1000 -- Lily Student: 118 -- Tom Student: 460 -- Jack Student: 51 -- Xiaoming ============ after sorting by name ======== Student: 460 -- Jack Student: 1000 -- Lily Student: 118 -- Tom Student: 51 -- Xiaoming

The Student class must implement the compareTo () method of the Comparable interface. The StudentComparator class must implement the compare () method of the Comparator interface:

Student. java

Package com. test. collection; import java. util. hashSet; import java. util. set;/*** Student class ** @ author Administrator **/public class Student implements Comparable <Student> {public String id; public String name; public Set <Course> courses; // public Student (String id, String name) {this. id = id; this. name = name; this. courses = new HashSet <Course> (); // instantiate sourses (Set is an interface and cannot be directly instantiated)} @ Override public int compareTo (Student o) {return this. id. compareTo (o. id );}}

StudentComparator. java

package com.test.collection;import java.util.Comparator;public class StudentComparator implements Comparator<Student> {    @Override    public int compare(Student o1, Student o2) {        return o1.name.compareTo(o2.name);    }}

 

Related Article

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.