html5企业网站建设,怎么使用vs2017做网站,网站重定向,当今做那些网站能致富在java开发中有时候我们需要对List集合中的元素按照一定的规则进行排序#xff0c;比如说有个Person的集合#xff0c;我们要根据Person的age属性进行排序输出#xff0c;这就需要用到Java中提供的对集合进行操作的工具类Collections#xff0c;其中的sort方法#xff0c;…在java开发中有时候我们需要对List集合中的元素按照一定的规则进行排序比如说有个Person的集合我们要根据Person的age属性进行排序输出这就需要用到Java中提供的对集合进行操作的工具类Collections其中的sort方法大家看虾米哥的例子如下 1.Person类 package www.itxm.cn;public class Person {private String id;private String name;private int age;public Person(String id, String name, int age) {super();this.id id;this.name name;this.age age;}public String getId() {return id;}public void setId(String id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public int getAge() {return age;}public void setAge(int age) {this.age age;}
}2.排序类 package www.itxm.cn;import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;public class PersonSort {public static void main(String[] args) {ListPerson plist new ArrayListPerson(); //创建3个Person对象年龄分别是32、20、25并将他们依次放入List中 Person p1 new Person(0001,zhangsan,32);Person p2 new Person(0002,lisi,20);Person p3 new Person(0003,wangwu,25);plist.add(p1);plist.add(p2);plist.add(p3);System.out.println(排序前的结果plist);Collections.sort(plist, new ComparatorPerson(){/** int compare(Person p1, Person p2) 返回一个基本类型的整型* 返回负数表示p1 小于p2* 返回0 表示p1和p2相等* 返回正数表示p1大于p2*/public int compare(Person p1, Person p2) {//按照Person的年龄进行升序排列if(p1.getAge() p2.getAge()){return 1;}if(p1.getAge() p2.getAge()){return 0;}return -1;}});System.out.println(排序后的结果plist); }
}3.总结 本排序最核心的Collections工具类的使用牢牢掌握遇到排序的时候不会手忙脚乱。转载于:https://www.cnblogs.com/wangyayun/p/7852075.html