Java集合排序

來源:互聯網
上載者:User

標籤:ids   技術   integer   tar   public   stat   res   資料類型   ide   

【 1.對普通的封裝類基礎資料型別 (Elementary Data Type)的list數組排序(Integer,Long,Double) 】

 Collections.sort(List list)

【例】

List<Long> musicIds = new ArrayList<>();musicIds.add(0, 1l);musicIds.add(1, 10l);musicIds.add(1, 2l);musicIds.add(1, 8l);musicIds.add(1, 4l);System.out.println("排序前:" + musicIds.toString());Collections.sort(musicIds);System.out.println("從小到大排序後:" + musicIds.toString());

【運行結果】

 

【 2.對普通的對象進行排序,根據對象中的某個成員變數(比如id) 】

 

public static void sort2(){    List<DataResponse> dataResponseList = Lists.newArrayList();    dataResponseList.add(new DataResponse(1001L,222));    dataResponseList.add(new DataResponse(1002L,444));    dataResponseList.add(new DataResponse(1003L,111));    dataResponseList.add(new DataResponse(1004L, 888));    Collections.sort(dataResponseList, new Comparator<DataResponse>() {        @Override        public int compare(DataResponse o1, DataResponse o2) {            return Integer.compare(o1.dataType, o2.dataType);        }    });    System.out.println("按dataType排序:\n" + dataResponseList.toString());    Collections.sort(dataResponseList, new Comparator<DataResponse>() {        @Override        public int compare(DataResponse o1, DataResponse o2) {            return Double.compare(o1.dataId,o2.dataId);        }    });    System.out.println("\n按dataId排序:\n"+dataResponseList.toString());}static class DataResponse{    Long dataId;    Integer dataType;    public DataResponse() {    }    public DataResponse(Long dataId, Integer dataType) {        this.dataId = dataId;        this.dataType = dataType;    }    public Long getDataId() {        return dataId;    }    public void setDataId(Long dataId) {        this.dataId = dataId;    }    public Integer getDataType() {        return dataType;    }    public void setDataType(Integer dataType) {        this.dataType = dataType;    }    @Override    public String toString() {        return "DataResponse{" +                "dataId=" + dataId +                ", dataType=" + dataType +                ‘}‘;    }}

【運行結果】

 

Java集合排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.