Java List Stream 排序:根据实体字段排序
在 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'}
代码解释:
- 创建一个
Entity类,包含id和name属性,并重写toString()方法以方便输出信息。 - 创建一个
List<Entity>,并添加一些Entity实例。 - 使用
stream()方法将List转换为Stream。 - 使用
sorted()方法对Stream进行排序,并传入Comparator对象。Comparator.comparingInt(Entity::getId)用于根据id字段升序排序。Comparator.comparing(Entity::getName).reversed()用于根据name字段降序排序。
- 使用
collect(Collectors.toList())方法将排序后的Stream重新转换为List。 - 输出排序结果。
结论:
Java Stream API 提供了方便的 sorted() 方法,可以根据指定的 Comparator 对 Stream 中的元素进行排序。通过使用 Comparator,可以轻松实现各种排序规则,例如根据特定字段升序或降序排序。
原文地址: https://www.cveoy.top/t/topic/qDDG 著作权归作者所有。请勿转载和采集!