当前位置 : 主页 > 手机开发 > android >

Android List(集合)中的对象以某一个字段排序案例

来源:互联网 收集:自由互联 发布时间:2021-05-09
在Android开发中,有时我们需要对一个对象的集合按照某一个字段进行排序, Bean public class Student { private int studentId; private String studentName; private int age; public Student(int studentId , String stude

在Android开发中,有时我们需要对一个对象的集合按照某一个字段进行排序,

Bean

public class Student {
 private int studentId;
 private String studentName;
 private int age;
 public Student(int studentId , String studentName, int age){
  this.studentId=studentId;
  this.studentName=studentName;
  this.age=age;
 }
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }

}

实现排序

实现排序比较类 Comparator ,里面实现排序规则。

public class test {

 /**
  * @param args
  */
 public static void main(String[] args) {
   Student stu1 = new Student (1,"zhangsan",28);
   Student stu2 = new Student (2,"zhagnsan",19);
   Student stu3 = new Student (3,"wangwu",19);
   Student stu4 = new Student (4,"wangwu",19);
   Student stu5 = new Student (5,"zhaoliu",18);

   ArrayList<Student> list = new ArrayList<Student>();
   list.add(stu1);
   list.add(stu2);
   list.add(stu3);
   list.add(stu4);
   list.add(stu5); 
//排序规则,这里是以年龄先排序,如果年龄相同
  Comparator<Student> comparator = new Comparator<Student>() {
   public int compare(Student s1, Student s2) {
    // 先排年龄
    if (s1.getAge() != s2.getAge()) {
     return s1.getAge() - s2.getAge();
    } else if (!s1.getStudentName().equals(s2.getStudentName())) {
     // 年龄相同则按姓名排序
     return s1.getStudentName().compareTo(s2.getStudentName());
    } else {
     // 姓名也相同则按学号排序
     return s1.getStudentId() - s2.getStudentId();
    }
   }
  };

   //这里就会自动根据规则进行排序
   Collections.sort(list,comparator);
   for(int i=0;i<list.size();i++){
    Student stu=list.get(i);
    System.out.println("年龄:"+stu.getAge()+" 姓名:"+stu.getStudentName()+" 学号:"+stu.getStudentId());
   }

 }

}

排序结果

结果:

年龄:18 姓名:zhaoliu 学号:5

年龄:19 姓名:wangwu 学号:3

年龄:19 姓名:wangwu 学号:4

年龄:19 姓名:zhagnsan 学号:2

年龄:28 姓名:zhangsan 学号:1

也可以想下面这样写:

 Collections.sort(list, new Comparator<GoodsBean>() {
   @Override
   public int compare(GoodsBean bean1, GoodsBean bean2) {

    if (Integer.valueOf(bean1.getScore()).compareTo(Integer.valueOf(bean2.getScore())) == 0) {
     return Integer.valueOf(bean1.getRecommend_num()).compareTo(Integer.valueOf(bean2.getRecommend_num()));
    } else {
     return Integer.valueOf(bean1.getScore()).compareTo(Integer.valueOf(bean2.getScore()));
    }
   }
  });

这样就可以对一个集合中的数据各种排序了。

补充知识:java利用映射表名称反射创建实体类并赋属性值

1.hibernate中首先进行初始化,将对应的表名和类名以键值对的方式存放到map中

  private Map<String, String> mappings;//全局变量

  /**
  * 根据数据库表名获取实体类
  */
  public void initMappings() {
    if (mappings == null) {
    mappings = new HashMap<String, String>();
    SessionFactory factory = this.getSessionFactory();
    Map metaMap = factory.getAllClassMetadata();
    for (String key : (Set<String>) metaMap.keySet()) {
      AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap.get(key);
      String tableName = classMetadata.getTableName().toLowerCase();
      int index = tableName.indexOf(".");
      if (index >= 0) {
        tableName = tableName.substring(index + 1);
      }
      String className = classMetadata.getEntityMetamodel().getName();
      mappings.put(tableName, className);
      }
    }
  }

2.调用方法,传入表名得到对应的实体类名

  public String getEntityNameByTableName(String tableName) {
    initMappings();
    return mappings.get(tableName);
  }

3.根据实体类名创建实体类

  /**
  *listobj:要赋的属性值集合,顺序要和实体类属性顺序一致

  */

  public Object getByReflect(String tableName, List listobj)throws Exception {

     Class<?> model = Class.forName(tableName);
     Object object = new Object();

      if (model != null) {
        Field[] field = model.getDeclaredFields();
       String[] modelName = new String[field.length];
        String[] modelType = new String[field.length];

       object = model.newInstance();
       Method m = null;

        for (int i = 1; i <field.length ; i++) {
          String name = field[i].getName();
          Object value = null;
         name = name.substring(0, 1).toUpperCase() + name.substring(1); 
          String type = field[i].getGenericType().toString(); 
           if (type.equals("class java.lang.String")) {
            m = model.getDeclaredMethod("set" + name, String.class);
  
            if(listobj.get(i - 1) instanceof Double){
               Double d=(Double) listobj.get(i-1);
               value=String.valueOf(d);
  
            }else{
              value =(String)listobj.get(i - 1);
            }
          }
          if (type.equals("class java.lang.Integer")) {
            m = model.getDeclaredMethod("set" + name, Integer.class);
            Double d = (Double) listobj.get(i - 1);
            value = Integer.valueOf(d.intValue());
          }
          if (type.equals("class java.lang.Short")) {
            m = model.getDeclaredMethod("set" + name, Short.class);
            value = (Short) listobj.get(i - 1);
          }
          if (type.equals("class java.lang.Float")) {
            m = model.getDeclaredMethod("set" + name, Float.class);
            value = (Float) listobj.get(i - 1);
          }
          if (type.equals("class java.lang.Double")) {
            m = model.getDeclaredMethod("set" + name, Double.class);
            value = (Double) listobj.get(i - 1);
          }
          if (type.equals("class java.lang.Boolean")) {
            m = model.getDeclaredMethod("set" + name, Boolean.class);
            value = (Boolean) listobj.get(i - 1);
          }
          if (m != null) {
            m.invoke(object, value);
       }
      }

    }
     return object;
   }

以上这篇Android List(集合)中的对象以某一个字段排序案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自由互联。

网友评论