侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

java如何对ArrayList中对象按照该对象某属性排序

2024-05-14 星期二 / 0 评论 / 0 点赞 / 87 阅读 / 10704 字

有几个方法可以实现:让 Student 实现Comparable接口,或是实例化一个比较器,现在用 Comparator 比较器实例来做一个: ComparableTest.Javaimport ja

有几个方法可以实现:让 Student 实现Comparable接口,或是实例化一个比较器,现在用 Comparator 比较器实例来做一个:

ComparableTest.Javaimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;public class ComparableTest { public static void main(String[] args) {    Comparator<Student> comparator = new Comparator<Student>(){     public int compare(Student s1, Student s2) {      //先排年龄      if(s1.age!=s2.age){       return s2.age-s1.age;      }      else{       //年龄相同则按姓名排序       if(!s1.name.equals(s2.name)){        return s2.name.compareTo(s1.name);       }       else{        //姓名也相同则按学号排序        return s2.id-s1.id;       }      }     }    };    Student stu1 = new Student (1,"zhangsan","male",28,"cs");    Student stu2 = new Student (2,"lisi","female",19,"cs");    Student stu3 = new Student (3,"wangwu","male",22,"cs");    Student stu4 = new Student (4,"zhaoliu","female",17,"cs");    Student stu5 = new Student (5,"jiaoming","male",22,"cs");    ArrayList<Student> List = new ArrayList<Student>();    List.add(stu1);    List.add(stu2);    List.add(stu3);    List.add(stu4);    List.add(stu5);     //这里就会自动根据规则进行排序    Collections.sort(List,comparator);    display(List);   }      static void display(ArrayList<Student> lst){    for(Student s:lst)     System.out.println(s);   }  }  class Student{   int age;   int id;   String gender;   String name;   String cs;   Student(int id,String name,String gender,int age,String cs){    this.age=age;    this.name=name;    this.gender=gender;    this.id=id;    this.cs=cs;   }   public String toString(){    return id+"  "+name+"  "+gender+"  "+age+"  "+cs;   }  }

2.添加 Comparable 接口,重写 compareTo 方法。然后你可以用 TreeSet 结构进行排序。它会自动排序。

实例:

Bean:

package chc;public class StuVo implements Comparable<StuVo>{  private String id;  private String name;  private Integer age;  public StuVo(String id, String name, Integer age) {    this.id=id;    this.name=name;    this.age=age;  }  public int compareTo(StuVo stu) {    return this.name.compareTo(stu.getName());  }  public String getId() {    return id;  }  public void setId(String id) {    this.id = id;  }  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public Integer getAge() {    return age;  }  public void setAge(Integer age) {    this.age = age;  }}

Demo:

package chc;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;public class ArrayListSortDemo {  public static void main(String[] args) {    List<StuVo> stuList=new ArrayList<StuVo>();    StuVo stu=new StuVo("1","h小明",11);    stuList.add(stu);        stu=new StuVo("2","d阿熊",15);    stuList.add(stu);        stu=new StuVo("3","a张三",10);    stuList.add(stu);        stu=new StuVo("4","b李四",15);    stuList.add(stu);      Collections.sort(stuList);        Iterator<StuVo> it =stuList.iterator();    while(it.hasNext()){      System.out.println(it.next().getName());    }  }}

项目中的代码:

    对材料代号displayCode排序,该值是个数字字符串,很长,可能存在小数点,所以使用bigdecimal来判断:

​            index = 1;            for(String key:endMap.keySet()){				pBudget0805 = endMap.get(key);				pBudget0805.setIndex(index+"");				data.add(pBudget0805);				index++;			};		    Comparator<ProjectBudget0805> comparator = new Comparator<ProjectBudget0805>(){			     public int compare(ProjectBudget0805 p1, ProjectBudget0805 p2) {			        return new BigDecimal(p2.getDisplayCode()).compareTo(new BigDecimal(p1.getDisplayCode()));			     }		    };			Collections.sort(data,comparator);​​index = 1;			for(String key:endMap.keySet()){				pBudget0805 = endMap.get(key);				pBudget0805.setIndex(index+"");				data.add(pBudget0805);				index++;			};		    Comparator<ProjectBudget0805> comparator = new Comparator<ProjectBudget0805>(){			     public int compare(ProjectBudget0805 p1, ProjectBudget0805 p2) {			        return new BigDecimal(p2.getDisplayCode()).compareTo(new BigDecimal(p1.getDisplayCode()));			     }		    };			Collections.sort(data,comparator);            //循环排序后的data,设置记录正确的index,再放入到一个新的data1中            index = 1;            for(ProjectBudget0805 p:data){				p.setIndex(index+"");				data1.add(pBudget0805);				index++;			};           //data1就是我们想要的结果​

通过这个可以发现list集合中是按照displayCode的升序来排列的.

但是这么做有一个确定,要循环两次,才能得出记录正确的index索引号,改良后的写法:

            index = 1;//			for(String key:endMap.keySet()){//				pBudget0805 = endMap.get(key);//				pBudget0805.setIndex(index+"");//				data.add(pBudget0805);//				index++;//			};			List<Entry<String, ProjectBudget0805>> endList = new ArrayList<>(endMap.entrySet());		    Comparator<Map.Entry<String, ProjectBudget0805>> comparator = new Comparator<Map.Entry<String, ProjectBudget0805>>(){			     public int compare(Map.Entry<String, ProjectBudget0805> o1,Map.Entry<String, ProjectBudget0805> o2) {			    	String p1 = o1.getValue().getDisplayCode();			    	String p2 = o2.getValue().getDisplayCode();			        return new BigDecimal(p2).compareTo(new BigDecimal(p1));			     }		    };			Collections.sort(endList,comparator);            //这里是先排序,然后设置正确的索引号,不需要创建新的data1对象来放置data中的内容			for(Entry<String, ProjectBudget0805> entity:endList){				pBudget0805 = entity.getValue();				pBudget0805.setIndex(index+"");				data.add(pBudget0805);				index++;			}

附上一篇关于Map的文章:

java中的Map结构是key->value键值对存储的,而且根据Map的特性,同一个Map中不存在两个Key相同的元素,而value不存在这个限制。换句话说,在同一个Map中Key是唯一的,而value不唯一。Map是一个接口,我们不能直接声明一个Map类型的对象,在实际开发中,比较常用的Map性数据结构是HashMap和TreeMap,它们都是Map的直接子类。如果考虑到存取效率的话,建议使用HashMap数据结构,而如果需要考虑到Key的顺序,建议使用TreeMap,但是TreeMap在删除、添加过程中需要排序,性能比较差。

1.以Key进行排序

//我们可以声明一个TreeMap对象Map<Integer, Person> map = new TreeMap<Integer, Person>();//然后往map中添加元素,可以通过输出结果,可以发现map里面的元素都是排好序的//遍历集合for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {    Person person = map.get(it.next());    System.out.println(person.getId_card() + " " + person.getName());}//我们也可以声明一个HashMap对象,然后把HashMap对象赋值给TreeMap,如下:Map<Integer, Person> map = new HashMap<Integer, Person>();TreeMap treemap = new TreeMap(map);

2.以Value进行排序:

​//先声明一个HashMap对象:Map<String, Integer> map = new HashMap<String, Integer>();//然后我们可以将Map集合转换成List集合中,而List使用ArrayList来实现如下:List<Entry<String,Integer>> list =    new ArrayList<Entry<String,Integer>>(map.entrySet());//最后通过Collections.sort(List l, Comparator c)方法来进行排序,代码如下:Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {    public int compare(Map.Entry<String, Integer> o1,            Map.Entry<String, Integer> o2) {        return (o2.getValue() - o1.getValue());    }});​

上述代码是讲map中的value按照逆序排序,如果需要按照升序进行排序的话,只需要修改o2.getValue() - o1.getValue()为o1.getValue() - o2.getValue()即可

在排序规则中也可以加上另外的条件,例如:

Comparator<ProjectBudget0708_1> comparator = new Comparator<ProjectBudget0708_1>(){		     public int compare(ProjectBudget0708_1 p1, ProjectBudget0708_1 p2) {		    	 BigDecimal index1 = p1.getIndex2();		    	 BigDecimal index2 = p2.getIndex2();		    	 //如果被比较的两个数都包含小数点(即定额下挂靠的消耗的排序)		    	 if(index1.toString().contains(".") && index2.toString().contains(".")){		    		 String str1 = index1.toString();		    		 String str2 = index2.toString();		    		 String subStr1 = str1.substring(0, str1.indexOf("."));		    		 String subStr2 = str2.substring(0, str2.indexOf("."));		    		 //如果subStr1等于subStr2,表示两个消耗在同一个定额下,那么根据两个消耗的displayCode排序;其余的情况都是通过index2进行排序		    		 if(subStr1.equals(subStr2)){		    			 return new BigDecimal(p1.getListCode()).compareTo(new BigDecimal(p2.getListCode()));		    		 }		    	 };		        return p1.getIndex2().compareTo(p2.getIndex2());		     }	    };Collections.sort(data,comparator);

另外再说个例子:

比如有两个list每个list中的元素是同种类型,都为object[]数组,现在要把这两个list组合到一起,按照object中的某个属性按照顺序显示,

方法1.可以循环每个list,然后添加两个list中的元素,在添加的时候注意排除掉已经添加过的元素即可,最后用compare比较器定义比较规则,最后按照规则进行排序.

方法2.利用treeSet,treeSet是有序的,不能用hashSet

TreeSet<Object[]> set = new TreeSet<Object[]>(new Comparator<Object[]>(){        public int compare(Object[] p1, Object[] p2) {            int num = ((BigInteger)p1[16]).compareTo((BigInteger)p2[16]);            return num;        }});String secUid = "";if(list != null){	for(Object[] object:list){		secUid = (String)object[0];		set.add(object);	}}if(list1 != null){	for(Object[] object:list1){		secUid = (String)object[0];		set.add(object);	}}

在treeSet添加元素的时候,就已经按照里面object[]数组中的某个元素的值排好序了

广告 广告

评论区