Objects in the Android List of collection sort cases by one field

  • 2021-12-05 07:22:12
  • OfStack

In Android development, sometimes we need to sort a collection of 1 object according to a certain 1 field.

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

}

Implement sorting

Realize sorting comparison class Comparator, which realizes sorting rules.


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); 
// Sorting rules, here are sorted by age first, if the ages are the same 
  Comparator<Student> comparator = new Comparator<Student>() {
   public int compare(Student s1, Student s2) {
    //  Age first 
    if (s1.getAge() != s2.getAge()) {
     return s1.getAge() - s2.getAge();
    } else if (!s1.getStudentName().equals(s2.getStudentName())) {
     //  If the age is the same, it will be sorted by name 
     return s1.getStudentName().compareTo(s2.getStudentName());
    } else {
     //  If the names are the same, they will be sorted by student number 
     return s1.getStudentId() - s2.getStudentId();
    }
   }
  };

   // It will be sorted automatically according to the rules 
   Collections.sort(list,comparator);
   for(int i=0;i<list.size();i++){
    Student stu=list.get(i);
    System.out.println(" Age :"+stu.getAge()+"  Name :"+stu.getStudentName()+"  Student number :"+stu.getStudentId());
   }

 }

}

Sort result

Results:

Age: 18 Name: zhaoliu Student Number: 5

Age: 19 Name: wangwu Student Number: 3

Age: 19 Name: wangwu Student Number: 4

Age: 19 Name: zhagnsan Student Number: 2

Age: 28 Name: zhangsan Student Number: 1

You can also want to write as follows:


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

In this way, the data in a collection can be sorted in various ways.

Additional knowledge: java uses mapping table name reflection to create entity classes and assign attribute values

1. In hibernate, initialization is carried out firstly, and the corresponding table name and class name are stored in map in the way of key-value pair


    private Map<String, String> mappings;// Global variable 

    /**
    *  Getting Entity Classes Based on Database Table Names 
    */
    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. Call the method and pass in the table name to get the corresponding entity class name


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

3. Create Entity Class Based on Entity Class Name


        /**
        *listobj: The set of attribute values to be assigned, the order should be the same as the entity class attribute order 1 To 

        */

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

Related articles: