您的位置:首页 > 编程语言 > Java开发

Java对List集合中的元素进行排序

2018-03-27 20:36 633 查看

前言

可以进行String,Date,Integer等类型进行排序,这里以数值类型为例子。

创建Bean类

package www.itxm.net;

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;
}
}

排序类

package www.itxm.net;

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<Person> plist = new ArrayList<Person>();
//创建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<Person>(){
/*
* 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);
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: