當前位置:首頁 » 編程語言 » java欄位排序

java欄位排序

發布時間: 2023-01-09 13:47:47

java的list集合如何根據對象中的某個欄位排序

下面的代碼是根據學生年齡排序學生list 的一個例子:

importjava.util.ArrayList;
importjava.util.List;

classStudent{

privateStringname;

privateintage;

publicStudent(Stringname,intage){
this.name=name;
this.age=age;
}

publicStringgetName(){
returnname;
}

publicvoidsetName(Stringname){
this.name=name;
}

publicintgetAge(){
returnage;
}

publicvoidsetAge(intage){
this.age=age;
}

@Override
publicStringtoString(){
return"Perosn[name="+name+",age="+age+"]";
}
}

publicclassApp{

publicstaticvoidmain(String[]args){

List<Student>students=newArrayList<>();

students.add(newStudent("abc",12));
students.add(newStudent("bcd",20));
students.add(newStudent("cde",17));
students.add(newStudent("def",25));
students.add(newStudent("efg",15));

students.sort((x,y)->Integer.compare(x.getAge(),y.getAge()));

for(Studentstu:students){
System.out.println(stu);
}
}
}

運行結果:

② java 中 List<T>如何按照T中的一個欄位排序

可以通過以下工具類進行實現:
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* List按照指定欄位排序工具類
*
* @param <T>
*/
public class ListSortUtil<T> {
/**
* @param targetList 目標排序List
* @param sortField 排序欄位(實體類屬性名)
* @param sortMode 排序方式(asc or desc)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sort(List<T> targetList, final String sortField, final String sortMode) {

Collections.sort(targetList, new Comparator() {
public int compare(Object obj1, Object obj2) {
int retVal = 0;
try {
//首字母轉大寫
String newStr=sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w","");
String methodStr="get"+newStr;

Method method1 = ((T)obj1).getClass().getMethod(methodStr, null);
Method method2 = ((T)obj2).getClass().getMethod(methodStr, null);
if (sortMode != null && "desc".equals(sortMode)) {
retVal = method2.invoke(((T) obj2), null).toString().compareTo(method1.invoke(((T) obj1), null).toString()); // 倒序
} else {
retVal = method1.invoke(((T) obj1), null).toString().compareTo(method2.invoke(((T) obj2), null).toString()); // 正序
}
} catch (Exception e) {
throw new RuntimeException();
}
return retVal;
}
});
}

}

Collections.sort(list.);//升序

③ java如何讓list按照list裡面的某個欄位排序,list裡面的有很多欄位!

給你個例子看下

importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Comparator;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

publicclass${

publicstaticvoidmain(String[]args){

List<Map<String,Integer>>data=newArrayList<Map<String,Integer>>();

init(data);

System.out.println("排序前:");
System.out.println(data);
sort(data);
System.out.println("排序後:");
System.out.println(data);
}

privatestaticvoidsort(List<Map<String,Integer>>data){

Collections.sort(data,newComparator<Map>(){

publicintcompare(Mapo1,Mapo2){

Integera=(Integer)o1.get("PRECOUNTOUT");
Integerb=(Integer)o2.get("PRECOUNTOUT");

//升序
returna.compareTo(b);

//降序
//returnb.compareTo(a);
}
});
}

privatestaticvoidinit(List<Map<String,Integer>>data){

Map<String,Integer>map=newHashMap<String,Integer>();
map.put("COUNTTICKET",1);
map.put("PRECOUNTOUT",2);
data.add(map);

map=newHashMap<String,Integer>();
map.put("COUNTTICKET",6);
map.put("PRECOUNTOUT",7);
data.add(map);

map=newHashMap<String,Integer>();
map.put("COUNTTICKET",8);
map.put("PRECOUNTOUT",5);
data.add(map);

map=newHashMap<String,Integer>();
map.put("COUNTTICKET",2);
map.put("PRECOUNTOUT",3);
data.add(map);
}
}

④ java怎樣對集合按照實體類的欄位排序

如果是實體類你可以通過資料庫查詢排序,這里就不多說了
如果已經得到結果了你可以通過編寫一個對象比較器來實現排序
代碼參考如下
package com.ljq.entity;

/**
* 運號單流程
*
* @author Administrator
*
*/
public class Step{
/** 處理時間 */
private String acceptTime = "";
/** 快件所在地點 */
private String acceptAddress = "";

public Step() {
super();
}

public Step(String acceptTime, String acceptAddress) {
super();
this.acceptTime = acceptTime;
this.acceptAddress = acceptAddress;
}

public String getAcceptTime() {
return acceptTime;
}

public void setAcceptTime(String acceptTime) {
this.acceptTime = acceptTime;
}

public String getAcceptAddress() {
return acceptAddress;
}

public void setAcceptAddress(String acceptAddress) {
this.acceptAddress = acceptAddress;
}

}

復制代碼

二、實現Comparator介面
復制代碼

package com.ljq.entity;

import java.util.Comparator;
import java.util.Date;

import com.ljq.util.UtilTool;

/**
* 對Step類進行排序
*
* @author Administrator
*
*/
public class StepComparator implements Comparator<Step>{

/**
* 如果o1小於o2,返回一個負數;如果o1大於o2,返回一個正數;如果他們相等,則返回0;
*/
@Override
public int compare(Step o1, Step o2) {
Date acceptTime1=UtilTool.strToDate(o1.getAcceptTime(), null);
Date acceptTime2=UtilTool.strToDate(o2.getAcceptTime(), null);

//對日期欄位進行升序,如果欲降序可採用before方法
if(acceptTime1.after(acceptTime2)) return 1;
return -1;
}

}

復制代碼

三、測試
復制代碼

package junit;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

public class StepComparatorTest {

@Test
public void sort() throws Exception{
List<Step> steps=new ArrayList<Step>;
//對集合對象進行排序
StepComparator comparator=new StepComparator();
Collections.sort(steps, comparator);
if(steps!=null&&steps.size()>0){
for(Step step:steps){
System.out.println(step.getAcceptAddress());
System.out.println(step.getAcceptTime());
}
}

}
}

熱點內容
以下所列的c語言常量中錯誤的是 發布:2025-07-10 16:19:00 瀏覽:850
怎麼給安卓應用重命名 發布:2025-07-10 16:18:01 瀏覽:998
php調用棧 發布:2025-07-10 15:58:33 瀏覽:869
android頁面返回 發布:2025-07-10 15:58:22 瀏覽:460
php解析多層json 發布:2025-07-10 15:51:36 瀏覽:873
谷歌x86版安卓系統哪個最流暢 發布:2025-07-10 15:51:33 瀏覽:445
iqoo清除應用緩存 發布:2025-07-10 15:34:34 瀏覽:845
手機rm文件夾 發布:2025-07-10 15:30:48 瀏覽:581
游戲腳本掛 發布:2025-07-10 15:21:46 瀏覽:588
sql寫數據 發布:2025-07-10 15:01:29 瀏覽:163