2019独角兽企业重金招聘Python工程师标准>>>
List<Bean> 简单排序如下:
1.创建Bean
package com.nzh.Demo.entity;
/**
* @comment:学生实体类
* @author 傅里叶级数
* @date 2018年
*/
public class StudentsBean {
/**
* 身高
*/
private float height;
/**
* 年龄
*/
private int age;
/**
* 血型
*/
private String bloodType;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private String sex;
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2.写排序的Demo
package com.nzh.Demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.nzh.Demo.entity.StudentsBean;
public class StudentDemo {
public static void main(String[] args) {
/**
* 声明学生实体
*/
StudentsBean student1 = new StudentsBean();
StudentsBean student2 = new StudentsBean();
StudentsBean student3 = new StudentsBean();
StudentsBean student4 = new StudentsBean();
/**
* 赋值
*/
student1.setName("张三");
student1.setSex("男");
student1.setAge(12);
student1.setBloodType("B");
student1.setHeight(180);
student2.setName("李四");
student2.setSex("男");
student2.setAge(34);
student2.setBloodType("O");
student2.setHeight(183);
student3.setName("王五");
student3.setSex("女");
student3.setAge(32);
student3.setBloodType("A");
student3.setHeight(179);
student4.setName("赵六");
student4.setSex("女");
student4.setAge(24);
student4.setBloodType("AB");
student4.setHeight(175);
List<StudentsBean> listStd = new ArrayList<>();
listStd.add(student1);
listStd.add(student2);
listStd.add(student3);
listStd.add(student4);
listBeanSort(listStd);
printlnStuData(listStd);
}
/**
* 打印学生数据
*/
public static void printlnStuData(List<StudentsBean> listStd){
System.out.println("学生数据如下:");
for (StudentsBean stu : listStd) {
System.out.println("姓名:"+stu.getName()+" 性别:"+stu.getSex()+" 年龄:"+stu.getAge()+" 血型:"+stu.getBloodType()+" 身高:"+stu.getHeight());
}
}
/**
* @comment:ListBean 排序
* @author:傅里叶级数
* @date:2018年
* @param listStd
*/
public static void listBeanSort(List<StudentsBean> listStd){
Collections.sort(listStd,new Comparator<StudentsBean>() {
@Override
public int compare(StudentsBean o1, StudentsBean o2) {
// // 按照年龄升序排列
// return o1.getAge()-o2.getAge();
// // 按照年龄降序排列
// return o1.getAge()-o2.getAge();
// 按照身高排序,需要将float类型转换为int类型再排序,如果为String类型的数字,也需要将String类型的数字转换为int类型
int high1 = (int)o1.getHeight();
int high2 = (int)o2.getHeight();
return high1-high2;
}
});
}
}