java中list集合排序_java如何对List集合中的元素进行排序(请收藏)

在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) {

List plist = new ArrayList();

//创建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 Comparator(){

/*

* 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工具类的使用,牢牢掌握,遇到排序的时候不会手忙脚乱。


版权声明:本文为weixin_32299949原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。