在Java中,可以通过使用sorted()函数与Lambda表达式结合对集合进行排序
首先,确保已经导入了以下所需的类:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
接下来,创建一个简单的实体类,例如Person:
public 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 +
'}';
}
}
现在,创建一个Person对象的列表并使用sorted()函数对其进行排序。这里我们将使用两种不同的排序方法:按姓名排序和按年龄排序。
public class Main {
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));
// 按姓名排序(升序)
List<Person> sortedByName = people.stream()
.sorted((p1, p2) -> p1.getName().compareTo(p2.getName()))
.collect(Collectors.toList());
System.out.println("Sorted by name: " + sortedByName);
// 按年龄排序(升序)
List<Person> sortedByAge = people.stream()
.sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
.collect(Collectors.toList());
System.out.println("Sorted by age: " + sortedByAge);
}
}
运行上述代码,你将看到如下输出:
Sorted by name: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]
Sorted by age: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]
在这个示例中,我们使用了Lambda表达式作为sorted()函数的参数,以便根据需要对Person对象列表进行排序。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1126614.html