当前位置:网站首页>Call collections Sort() method, compare two person objects (by age ratio first, and by name ratio for the same age), and pass lambda expression as a parameter.
Call collections Sort() method, compare two person objects (by age ratio first, and by name ratio for the same age), and pass lambda expression as a parameter.
2022-06-30 02:39:00 【aigo-2021】
call Collections.sort() Method , Compare the two Person object ( First by age , The same age by name ), Use Lambda The expression is passed as an argument .
public class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// rewrite toString Method
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Person> list = Arrays.asList(new Person(" Xiao Liang ", 22),
new Person(" Li Si ", 23), new Person(" Xiao Ming ", 20),
new Person(" Zhang San ", 20));
//sort Method passes in a comparator Comparator<? super T> c
Collections.sort(list,(a, b) ->{
int num = Integer.compare(a.age, b.age);
int num2 = num==0?a.name.compareTo(b.name):num;
return num2; // Be sure to write when there are multiline expressions return
});
for (Person employee : employeeList) {
System.out.println(employee.toString());
}
}
}Running results :

边栏推荐
猜你喜欢

什么是X.509证书?X.509证书工作原理及应用?

福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点

Linear algebra Chapter 3 summary of vector and vector space knowledge points (Jeff's self perception)

Unity timeline data binding

代码签名、驱动签名的常见问题解答

What is certificate transparency CT? How to query CT logs certificate logs?

Detailed explanation of minimum stack

最小栈详解

Traffic, but no sales? 6 steps to increase website sales

直接插入排序
随机推荐
FAQs for code signature and driver signature
Cmake tutorial series -02- generating binaries using cmake code
Pytoch learning (II)
三层交换机和二层交换机区别是什么
Sitelock nine FAQs
What should academic presentation /ppt do?
快速排序
有流量,但没有销售?增加网站销量的 6 个步骤
选择排序
Shenzhen CPDA Data Analyst Certification in July 2022
NPDP产品经理国际认证考试报名有什么要求?
代码签名、驱动签名的常见问题解答
希尔排序
What is an X.509 certificate? 10. 509 certificate working principle and application?
Creating exquisite skills in maker Education
IBM WebSphere channel connectivity setup and testing
LeetCode 3. 无重复字符的最长子串
Insert sort directly
2. < tag dynamic programming and 0-1 knapsack problem > lt.416 Split equal sum subset + lt.1049 Weight of the last stone II
Linear algebra Chapter 4 Summary of knowledge points of linear equations (Jeff's self perception)