JAVA中List 排序
第一种方法,就是list中对象实现Comparable接口,代码如下:
public class SortEntity implements Comparable<SortEntity>{ private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int compareTo(SortEntity o) { return this.getName().compareTo(o.getName()); } }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; public class JUnitTest { @Test public void testSort(){ List<SortEntity> selist=new ArrayList<>(); SortEntity se=new SortEntity(); se.setName("abc"); se.setAge(50); selist.add(se); SortEntity se1=new SortEntity(); se1.setName("abd"); se1.setAge(13); selist.add(se1); SortEntity se2=new SortEntity(); se2.setName("aaa"); se2.setAge(324); selist.add(se2); SortEntity se3=new SortEntity(); se3.setName("abe"); se3.setAge(5); selist.add(se3); Collections.sort(selist); for (SortEntity s:selist) { System.out.println(s.getName()); } } }
第二种方法,就是在重载Collections.sort方法,代码如下:
public class SortEntity{ private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.junit.Test; public class JUnitTest { @Test public void testSort(){ List<SortEntity> selist=new ArrayList<>(); SortEntity se=new SortEntity(); se.setName("abc"); se.setAge(50); selist.add(se); SortEntity se1=new SortEntity(); se1.setName("abd"); se1.setAge(13); selist.add(se1); SortEntity se2=new SortEntity(); se2.setName("aaa"); se2.setAge(324); selist.add(se2); SortEntity se3=new SortEntity(); se3.setName("abe"); se3.setAge(5); selist.add(se3); Collections.sort(selist,new Comparator<SortEntity>() { @Override public int compare(SortEntity o1, SortEntity o2) { return o1.getName().compareTo(o2.getName()); } }); for (SortEntity s:selist) { System.out.println(s.getName()); } } }