在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'}
``
java list stream 根据实体的字段排序

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

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