java根据List内对象的属性排序⽅法⽅法⼀:实现Comparator接⼝,并重写compare⽅法
实体类代码:
import java.util.Comparator;
/**
* 学⽣类⽅法⼀
* 实现Comparator接⼝
* 并重写compare⽅法
* @author liaot
*
*/
public class Student implements Comparator<Student>{
private String name; //姓名
private int age; //年龄
//重写⽐较⽅法本次例⼦定义为按年龄⽐较
@Override
public int compare(Student o1, Student o2) {
Age() > o2.getAge()){
return 1;
}else{
return -1;
}
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
测试类:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
//初始化四个不同的学⽣
Student stu1 = new Student("路⼈甲", 20);
Student stu2 = new Student("路⼈已", 18);
Student stu3 = new Student("路⼈丙", 16);
Student stu4 = new Student("路⼈丁", 19);
//新建List把学⽣加进List
List<Student> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
stuList.add(stu4);
System.out.println("排序前:=====");
for(Student stu :stuList){
System.out.println("姓名:"+Name() +" 年龄"+Age());
}
//排序
Collections.sort(stuList, stu1); //第⼀个参数为List 第⼆个参数为对象的⼀个实例  System.out.println("排序后:=====");
for(Student stu :stuList){
System.out.println("姓名:"+Name() +" 年龄"+Age());
}
}
}
运⾏结果:
⽅法⼆:实现Comparable接⼝并重写compareTo⽅法
/**
* 学⽣类⽅法⼆实现Comparable接⼝并重写compareTo⽅法
*
* @author liaot
*
*/
public class Student2 implements Comparable<Student2> {
private String name; // 姓名
private int age; // 年龄
// 重写⽐较⽅法本次例⼦定义为按年龄⽐较
@Override
public int compareTo(Student2 stu) {
if (this.age > Age()) {
return 1;
} else {
return -1;
}
}
public Student2(String name, int age) {
super();
this.name = name;
this.age = age;
java arraylist用法}
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;
}
}
测试类
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main2 {
public static void main(String[] args) {
//初始化四个不同的学⽣
Student2 stu1 = new Student2("路⼈甲", 20);
Student2 stu2 = new Student2("路⼈已", 18);
Student2 stu3 = new Student2("路⼈丙", 16);
Student2 stu4 = new Student2("路⼈丁", 19);
//新建List把学⽣加进List
List<Student2> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
stuList.add(stu4);
System.out.println("排序前:=====");
for(Student2 stu :stuList){
System.out.println("姓名:"+Name() +" 年龄"+Age());
}
/
/排序
Collections.sort(stuList); //只有⼀个参数参数为List
System.out.println("排序后:=====");
for(Student2 stu :stuList){
System.out.println("姓名:"+Name() +" 年龄"+Age());
}
}
}
运⾏结果
三、总结:两种⽅式写法和⽤法上的区别:
以上这篇java根据List内对象的属性排序⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。