JavaCollections.sort()排序代码案例-创新互联
1、案例:

Person对象(名字,id,年龄)
要求按照,年龄从小到大排序,年龄相等,按照名字的字典顺序de倒序排序
2、案例设计:
1)使用ArrayList存储Person对象,
2)利用Collections.sort()进行排序
3)输出结果
3、代码分享:
package CollectionDemo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
class Person{
private int id;
private int age;
private String name;
public Person(int id, int age,String name){
this.id=id;
this.age=age;
this.name=name;
}
public void setId(int id) {
this.id = id;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name){
this.name=name;
}
public int getId() {
return id;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
public class CollectionDemo2 {
public static void main(String[] args){
List arrayList =new ArrayList<>();
arrayList.add(new Person(001,20,"yang"));
arrayList.add(new Person(002,20,"zhang"));
arrayList.add(new Person(003,30,"li"));
arrayList.add(new Person(004,40,"Coco"));
arrayList.add(new Person(005,40,"Marry"));
Collections.sort(arrayList,new Comparator(){
public int compare(Person o1,Person o2){
if(o1.getAge()!=o2.getAge()){
return o1.getAge()-o2.getAge();//按照年龄升序排序
}else{
return o2.getName().compareToIgnoreCase(o1.getName());//按照名字的字典顺序倒序排序
}
}
});
//输出
for(Person p:arrayList){
System.out.println(p);
}
}
} 另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前文章:JavaCollections.sort()排序代码案例-创新互联
文章起源:http://www.scyingshan.cn/article/cecoio.html


咨询
建站咨询
