To sort a single field or multiple fields in Java
Import Java.util.arraylist;import java.util.collections;import java.util.comparator;import java.util.List;/** * @ date:2015 June 19 Morning 10:11:44 */public class Collectiontest {/** * Main method * * @param args * parameter * @modify by User: {modifier} June 19, 2015 * @modify by reason:{cause} */public static void main (string[] args) { List<collectiontest.man> mans = New Arraylist<collectiontest.man> (); Collectiontest collectiontest = new Collectiontest (); Man mans = Collectiontest.new Man (); Man.setparentid (11); Man.setage (12); Man.setname ("xxx 1_ children"); Mans man2 = Collectiontest.new man (); Man2.setparentid (2); Man2.setage (13); Man2.setname ("xxx 2_ children"); Mans MAN3 = Collectiontest.new man (); Man3.setparentid (2); Man3.setage (16); Man3.setname ("xxx 1_ children"); Mans.add (man); Mans.add (MAN2); Mans.add (MAN3); Sortage (Mans); System.out.println ("*Sorted by age ******** "); System.out.println (Mans.tostring ()); Sortparentidage (Mans); SYSTEM.OUT.PRINTLN ("* * * * * * * Based on Parent ID, age ********"); System.out.println (Mans.tostring ()); }/** * Sorted by Parent ID, age * * @param mans * Person list * @modify by User: {modified by} June 19, 2015 * @m Odify by reason:{Reason} */private static void Sortparentidage (List<man> mans) {Collections.sort (Mans, N EW comparator<man> () {@Override public int compare (Mans O1, man O2) {if (o1.ge Tparentid (). Equals (O2.getparentid ())) {return o1.getage (). CompareTo (O2.getage ()); } else {return O1.getparentid (). CompareTo (O2.getparentid ()); } } }); }/** * Sorted by Parent ID * * @param mans * @modify by User: {modified by} June 19, 2015 * @modify by reason:{Reason} * /private static void Sortage (List<man> mans) {CollectioNs.sort (Mans, New Comparator<man> () {@Override public int compare (Mans O1, man O2) { Return O1.getage (). CompareTo (O2.getage ()); } }); } public class Man {private Integer parentid; Private Integer age; private String name; /** * Get parentid * * @return parentid ParentID */public Integer Getparentid () { return parentid; }/** * Set ParentID * * @param parentid * parentid * * Pub LIC void Setparentid (Integer parentid) {this.parentid = ParentID; }/** * Gets the age * @return The age of age */public Integer getage () {R Eturn age; }/** * Set age * @param age * age */public void Setage (Integer Age) {this.age = age; }/** * Gets name * * @return Name Name * * Public String getName () { return name; }/** * Set name * * @param name * Name * * public void Set Name (String name) {this.name = name; }/** * @return * @modify by User: {modifier} June 19, 2015 * @modify by reason:{cause} */ @Override public String toString () {return ' man [parentid= ' + ParentID + ", age=" + Age + ", name=" + name + "]"; } }}
Sort single or multiple fields in Java