Java中List的排序

來源:互聯網
上載者:User

標籤:

 

這裡是一個類中類去實現條件優先排序的問題

package com.sun;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Demo {public Demo() {// TODO Auto-generated constructor stub}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint a= 0;Dob db  = new Dob();Dob db1  = new Dob();Dob db2  = new Dob();db.setName("sun");db.setAge(20);db.setSex(3);db1.setName("zhi");db1.setAge(22);db1.setSex(1);db2.setName("yan");db2.setAge(21);db2.setSex(2);List<Dob> as = new ArrayList<Dob>();System.out.println("as="+as.size());as.add(db);as.add(db1);as.add(db2); Collections.sort(as, new Comparator<Dob>() {//比較。如果年齡不同先比較年齡 ,相同就比較性別            public int compare(Dob arg0, Dob arg1) {            int flg = arg0.getAge().compareTo(arg1.getAge());            if(flg==0){             return arg0.getSex().compareTo(arg1.getSex());            }else{             return arg0.getAge().compareTo(arg1.getAge());            }                           }        });for (Dob p : as) {            System.out.println(p.getName());            System.out.println(p.getAge());        }System.out.println("as="+as.size());}}class Dob {public String  name;public Integer age;public Integer sex;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;}public Integer getSex() {return sex;}public void setSex(Integer sex) {this.sex = sex;}}

  

Java中List的排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.