Recently encountered a problem with list sorting, using Collection.sort ()
The following is my own practice, recording
package com.junit.test;import java.util.arraylist;import java.util.collections;import java.util.comparator;import java.util.iterator;import java.util.list;public class Collectionstest {public static void main (String[] args) {CollectionsTest c = new collectionstest (); List<student> stlist = new arraylist<student> (); Student s1 = c.new student (S1.setage); S1.setname ("GroupB"); S1.setsex ("Nan4"); S5.setage ("Student s5 = c.new student"), S5.setname ("GroupB"), S5.setsex ("Nan4"); Student s2 = c.new student (), S2.setage ("a"), S2.setname ("GROUPC"); S2.setsex ("Nan1"); S3.setage ("Student s3 = c.new student"), S3.setname ("Groupa"), S3.setsex ("nan2"); Student s4 = c.new student (); S4.setage ("n"), S4.setname ("Groupg"); S4.setsex ("nan6"); Stlist.add (S1); Stlist.add (S2); Stlist.add (S3); Stlist.add (S4); Stlist.add (S5); Iterator iter = stlist.iterator (); while (Iter.hasnext ()) {Student st = (Student) iter.next (); System.out.println (St.getname () + " " +st.getage () + " " + St.getsex ());} System.out.println ("---------------------------------------------"); Collections.sort (Stlist, c.new compartor1 ()); Iterator iter1 = stlist.iterator (); while (Iter1.hasnext ()) {student st1 = (Student) iter1.next (); System.out.println (St1.getname () + " " +st1.getage () + " " + St1.getsex ());}} Public class compartor1 implements comparator<student>{public int compare ( STUDENT&NBSP;O1,&NBSP;STUDENT&NBSP;O2) {string name1 = o1.getname (); String name2 = o2.getname ();//first by name Ascending if (Name1.compareto (name2) >0) {return 1;} Else if (Name1.compareto (name2) <0) {return -1;} else{Then sort string age1 = o1.getage () in descending order of age; String age2 = o2.getage (); if (Age1.compareto (age2) >0) {return -1;} Else if (Age1.compareto (age2) <0) {return 1;}} return 0;}} Public class student{public string name;public string age;public string sex;public string getname () {return name;} Public void setname (String name) {this.name = name;} Public string getage () {return age;} Public void setage (String age) {this.age = age;} Public string getsex () {return sex;} Public void setsex (String sex) {this.sex = sex;}}
This article is from the "Riding monkey on the Tree" blog, please be sure to keep this source http://qihoushangshu.blog.51cto.com/7872138/1612684
Java sorts the data in a list