栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Collections.sort()排序代码案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Collections.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);
    }
  }
}

输出:

Person{id=2, age=20, name='zhang'}
Person{id=1, age=20, name='yang'}
Person{id=3, age=30, name='li'}
Person{id=5, age=40, name='Marry'}
Person{id=4, age=40, name='Coco'}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号