摘要:java listj
單一欄位排序:
Collections.sort(resultList,new Comparator<MonthSalaryEbo>(){
public int compare(MonthSalaryEbo o1, MonthSalaryEbo o2) {
if (o1.getEmpId() != null && o2.getEmpId() != null) {
return Integer.parseInt(o1.getEmpId()) - Integer.parseInt(o2.getEmpId());
}
return 0;
}
});
多個欄位排序:
Collections.sort(listMonthSalary, new Comparator<SalaryEbo>(){
public int compare(SalaryEbo o1, SalaryEbo o2) {
if (o1.getOpUnitId()!=null && o2.getOpUnitId()!=null) {
if(!o1.getOpUnitId().equals(o2.getOpUnitId())){
return o1.getOpUnitId().compareTo(o2.getOpUnitId());
}else{
if (o1.getEptCode()!=null && o2.getEptCode()!=null) {
if(!o1.getEptCode().equals(o2.getEptCode())){
return o1.getEptCode().compareTo(o2.getEptCode());
}else{
return 0;
}
}
return 0;
}
}
//一組數字由小到大排序
int x[]=new int[]{9,8,6,4,0,10,3,2,1,5,7};
for(int i=0;i<10;i++)
{
for(int j=i+1;j<11;j++) Test.zip
{
if(x[i]>x[j])
{
int n=x[i];
x[i]=x[j];
x[j]=n;
}
////////////////////////////////////////////////
Map<String, MyBean> m;
m = new HashMap<String, MyBean>();
//我有一個叫MyBean的物件, 裡面有三個屬性分別為姓名, 科目, 分數
//我現在要先依照姓名排, 再依照分數排
MyBean bean = new MyBean();
bean.seteName("Edward");
bean.setScore(40);
bean.setItem("Chinese");
m.put("1", bean);
bean = new MyBean();
bean.seteName("Amy");
bean.setScore(90);
bean.setItem("Math");
m.put("3", bean);
bean = new MyBean();
bean.seteName("Edward");
bean.setScore(30);
bean.setItem("Math");
m.put("2", bean);
bean = new MyBean();
bean.seteName("Amy");
bean.setScore(100);
bean.setItem("Chinese");
m.put("4", bean);
//把Map轉成List
List<Map.Entry<String, MyBean>> list_Data = new ArrayList<Map.Entry<String, MyBean>>(m.entrySet());
//依照姓名排
Collections.sort(list_Data, new Comparator<Map.Entry<String, MyBean>>() {
public int compare(Map.Entry<String, MyBean> entry1, Map.Entry<String, MyBean> entry2) {
return (entry1.getValue().geteName().compareTo(entry2.getValue().geteName()));
}
});
for (Map.Entry<String, MyBean> entry : list_Data) {
System.out.println(entry.getValue().geteName());
System.out.println(entry.getValue().getItem());
System.out.println(entry.getValue().getScore());
}
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++");
//依照分數排
Collections.sort(list_Data, new Comparator<Map.Entry<String, MyBean>>() {
public int compare(Map.Entry<String, MyBean> entry1, Map.Entry<String, MyBean> entry2) {
return (entry2.getValue().getScore() - entry1.getValue().getScore());
}
});
for (Map.Entry<String, MyBean> entry : list_Data) {
System.out.println(entry.getValue().geteName());
System.out.println(entry.getValue().getItem());
System.out.println(entry.getValue().getScore());
}
}
}