温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-14 13:34:21 来源:脚本之家 阅读:117 作者:进进进出出 栏目:编程语言

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<Person> 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<Person>(){
      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'}

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI