List集合的排序实现

[color=blue]java中关于list的集合的排序实现方式:[/color]
[color=green][b]实现方法一:实体类实现comparable接口[/b][/color]
[color=darkblue] public class User implements Comparable<User>{
private String name;
private Integer age;
此处省略get、set方法
@Override
public int compareTo(User o) {
return this.getAge().compareTo(o.getAge());
}
}[/color]
[color=green][b]测试方法:[/b][/color]
[color=darkblue]public class ComparatorUser {
public static void main(String[] args0) {
List<User> list = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
int age = new Random().nextInt(100);
System.out.println("age:" + age);
String[] str = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M","N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
String name = "";
for (int k = 0; k < 6; k++) {
name += str[new Random().nextInt(47)];
}
System.out.println("name:" + name);
User u = new User();
u.setAge(age);
u.setName(name);
list.add(u);
}
Collections.sort(list);
for (User user : list) {
System.out.println(user.getName() + ":" + user.getAge());
}
}
}[/color]
实现方法二:继承comparator接口
[color=orange] 此处省略Student对象的创建代码。[/color]
[color=darkblue] public class ComparatorStudent implements Comparator<Student> {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
for (int i = 0; i < 10; i++) {
int age = new Random().nextInt(100);
System.out.println("age:" + age);
String[] str = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M","N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
String name = "";
for (int k = 0; k < 6; k++) {
name += str[new Random().nextInt(47)];
}
System.out.println("name:" + name);
Student u = new Student();
u.setAge(age);
u.setStuId(name);
list.add(u);
}
Comparator<Student> comparator = new ComparatorStudent();
Collections.sort(list, comparator);
for(Student stu : list){
System.out.println("stuID:"+stu.getStuId()+"age:"+stu.getAge())
}
}

/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Student o1, Student o2) {
/**
* equals 0 : o1 = o2
* greater 0 : 01 > 02
* less 0 : o1 < o2
*/
int flag = o1.getAge().compareTo(o2.getAge());
return flag;
}
}[/color]

在以上实现方法中,数值类的比较,只能是Integer类型,在Comparator接口中,指定的数值比较类型为Integer类型,flag = Integer.comparaTo(Integer anothersValue),其返回值flag有三种值:=0,<0,>0


以上两种实现方法的结果是一样的 ,均可实现list集合的排序
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值