List User list = new ArrayList;listaddnew User12张三 11 年龄姓名listaddnew User18李四11 年龄姓名用lambda 表达式用年龄从大到小排序用逗号分割返回姓名字符串
To sort the list of users by age in descending order and return a comma-separated string of names, you can use lambda expressions in Java. Here's an example:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User(12, "张三"));
list.add(new User(18, "李四"));
String sortedNames = list.stream()
.sorted(Comparator.comparingInt(User::getAge).reversed())
.map(User::getName)
.collect(Collectors.joining(", "));
System.out.println(sortedNames);
}
}
class User {
private int age;
private String name;
public User(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Output:
李四, 张三
In the above code, we use the stream() method to convert the list into a stream of elements. Then, we use the sorted() method with a comparator that compares the users based on their age in descending order. Next, we use the map() method to extract only the names of the users. Finally, we use the collect() method with Collectors.joining(", ") to join the names into a single string separated by commas
原文地址: https://www.cveoy.top/t/topic/iFpe 著作权归作者所有。请勿转载和采集!