熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java中對象按照屬性排序

2022-06-13   來源: Java核心技術 

  項目中經常需要用到比如地區列表按照中文的拼音首字母排序但是有時候獲取到的地區列表是對象的形式有地區id地區名稱兩個屬性這裡主要涉及到兩個技術點

  對象按屬性排序中文按拼音首字母排序下面給出自己整理好的demo:

  import javatextCollator;

  import javautilArrayList;

  import javautilCollections;

  import javautilComparator;

  import monsbeanutilsBeanComparator;

  import llectionsComparatorUtils;

  import paratorsComparableComparator;

  import paratorsComparatorChain;

  public class CompareTipA  {

  private int  id;

  private String  name;

  private String age;

  @SuppressWarnings(unchecked

  public static void main(String []args) {

  ArrayList<Object> list = new ArrayList<Object>()

  listadd(new CompareTipA())

  listadd(new CompareTipA())

  listadd(new CompareTipA())

  listadd(new CompareTipA())

  listadd(new CompareTipA())

  listadd(new CompareTipA())

  Comparator mycmp = ComparableComparatorgetInstance()

  mycmp = ComparatorUtilsnullLowComparator(mycmp)

  //允許null

  mycmp = ComparatorUtilsreversedComparator(mycmp) //逆序

  ArrayList<Object> sortFields = new ArrayList<Object>()

  Comparator<Object> comparator=CollatorgetInstance(javautilLocaleCHINA)

  sortFieldsadd(new BeanComparator(namecomparator))  //name正序 (主)

  sortFieldsadd(new BeanComparator(id mycmp))

  //id逆序  (副)

  ComparatorChain multiSort = new ComparatorChain(sortFields)

  Collectionssort(listmultiSort)

  for (int i =;i<listsize()i++) {

  Systemoutprintln(listget(i))

  //輸出   /*

  [id=name=二age=]

  [id=name=六age=]

  [id=name=四age=]

  [id=name=四age=]

  [id=name=五age=]

  [id=name=一age=]*/

  }

  }

  public CompareTipA(int id String ageString name) {

  thisid = id;

  thisname = name;

  thisage = age;

  }

  public int getId() {

  return thisid;

  }

  public void setId(int id) {

  thisid = id;

  }

  public String getName() {

  return thisname;

  }

  public void setName(String name) {

  thisname = name;

  }

  //

  public int compareTo(Object o) {   //

  return pare(this o)   //    }

  public String toString() {

  return [id= + thisid + name= + thisname +age= + thisage +];

  }

  public String getAge() {

  return age;

  }

  public void setAge(String age) {

  thisage = age;

  }   }

  注意需要導入的三個包commonsbeanutilsjar

  commonscollectionsjar

  commonsloggingjar

  commonscollections包不能用官網上的版本因為從源碼中可以看見commonsbeanutils包調用的就是commonscollections版本的api的沒兼容commonslogging包也是commonsbeanutils包所需要的


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25790.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.