一个list集合里面放实体类,我现在要根据实体类中的一个属性排序,给我一段java代码
时间: 2024-05-02 19:20:31 浏览: 10
Sure, here is the Java code to sort a list of entities by a specific property:
```
import java.util.List;
import java.util.Collections;
public class Entity {
private String name;
private int age;
// getters and setters
public Entity(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
// create a list of entities
List<Entity> entityList = List.of(
new Entity("Alice", 25),
new Entity("Bob", 30),
new Entity("Charlie", 20)
);
// sort the list by age
Collections.sort(entityList, (e1, e2) -> e1.getAge() - e2.getAge());
// print the sorted list
entityList.forEach(entity -> System.out.println(entity.getName() + " " + entity.getAge()));
}
}
```
In this example code, I created a class called `Entity` with `name` and `age` properties. I then created a list of `Entity` objects and sorted them by age using `Collections.sort()` method and a lambda expression. Finally, I printed out the sorted list.