在 Java 中,可以使用 Stream API 对 List 中的实体按照特定字段进行排序。以下是一个示例代码:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class Entity {
    private int id;
    private String name;

    public Entity(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

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

public class Main {
    public static void main(String[] args) {
        List<Entity> entities = new ArrayList<>();
        entities.add(new Entity(2, "John"));
        entities.add(new Entity(1, "Alice"));
        entities.add(new Entity(3, "Bob"));

        // 根据id字段升序排序
        List<Entity> sortedById = entities.stream()
                .sorted(Comparator.comparingInt(Entity::getId))
                .collect(Collectors.toList());
        System.out.println("Sorted by id:");
        sortedById.forEach(System.out::println);

        // 根据name字段降序排序
        List<Entity> sortedByName = entities.stream()
                .sorted(Comparator.comparing(Entity::getName).reversed())
                .collect(Collectors.toList());
        System.out.println("Sorted by name:");
        sortedByName.forEach(System.out::println);
    }
}

输出结果:

Sorted by id:
Entity{id=1, name='Alice'}
Entity{id=2, name='John'}
Entity{id=3, name='Bob'}
Sorted by name:
Entity{id=3, name='Bob'}
Entity{id=1, name='Alice'}
Entity{id=2, name='John'}

代码解释:

  1. 创建一个 Entity 类,包含 idname 属性,并重写 toString() 方法以方便输出信息。
  2. 创建一个 List<Entity>,并添加一些 Entity 实例。
  3. 使用 stream() 方法将 List 转换为 Stream
  4. 使用 sorted() 方法对 Stream 进行排序,并传入 Comparator 对象。
    • Comparator.comparingInt(Entity::getId) 用于根据 id 字段升序排序。
    • Comparator.comparing(Entity::getName).reversed() 用于根据 name 字段降序排序。
  5. 使用 collect(Collectors.toList()) 方法将排序后的 Stream 重新转换为 List
  6. 输出排序结果。

结论:

Java Stream API 提供了方便的 sorted() 方法,可以根据指定的 ComparatorStream 中的元素进行排序。通过使用 Comparator,可以轻松实现各种排序规则,例如根据特定字段升序或降序排序。

Java List Stream 排序:根据实体字段排序

原文地址: https://www.cveoy.top/t/topic/qDDG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录