Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java list 对象排序

作者:嗜血之舞   发布日期:2025-04-07   浏览:120

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class ListSortExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // 按年龄升序排序
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return Integer.compare(p1.getAge(), p2.getAge());
            }
        });

        System.out.println("按年龄升序排序后的列表:");
        for (Person person : people) {
            System.out.println(person);
        }

        // 按姓名字母顺序排序
        people.sort(Comparator.comparing(Person::getName));

        System.out.println("按姓名字母顺序排序后的列表:");
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

解释说明:

  1. 定义 Person:包含两个属性 nameage,并提供构造函数、getter 方法和 toString 方法。
  2. 创建 List<Person> 列表:使用 ArrayList 创建一个 Person 对象的列表,并添加一些示例数据。
  3. 按年龄升序排序:使用 Collections.sort 方法和自定义的 Comparator 来根据 age 属性对列表进行排序。
  4. 按姓名字母顺序排序:使用 List.sort 方法和 Comparator.comparing 方法来根据 name 属性对列表进行排序。
  5. 输出排序结果:通过遍历列表并调用 toString 方法打印排序后的结果。

上一篇:java聊天室代码

下一篇:java 静态代码块

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站