Java集合排序
【 1.对普通的包装类基本数据类型的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 + '}'; } }
【运行结果】