java中如何按名字来排序,如何在Java中对名称和年龄进行排序

这篇博客讨论了如何使用Java8对包含姓名和年龄的人员列表进行排序。原始代码只根据年龄进行了排序,但需求是当姓名重复时,根据年龄排序。解决方案是利用Java8的`Comparator.comparing`和`thenComparingInt`方法,首先按姓名排序,如果姓名相同则按年龄排序。这样可以确保输出如预期的排序结果。
摘要由CSDN通过智能技术生成

I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.

For example my input is

tarun 28

arun 29

varun 12

arun 22

and the output should be

arun 22

arun 29

tarun 28

varun 12

But I get something like

varun 12

arun 22

tarun 28

arun 29

Means it's sorted either only by ages or names.

This is the code which is implemented:

POJO class:

class Person {

String fname;

int age;

public Person() {

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getFname() {

return fname;

}

public void setFname(String fname) {

this.fname = fname;

}

public Person(String fname, int age) {

this.fname = fname;

this.age = age;

}

@Override

public String toString() {

return fname + age;

}

}

Test class:

public class Test {

public static void main(String[] args) {

List persons = new ArrayList<>();

persons.add(new Person("tarun", 28));

persons.add(new Person("arun", 29));

persons.add(new Person("varun", 12));

persons.add(new Person("arun", 22));

Collections.sort(persons, new Comparator() {

@Override

public int compare(Person t, Person t1) {

return t.getAge() - t1.getAge();

}

});

System.out.println(persons);

}

}

解决方案

Currently you are a) only comparing by one attribute and b) not really making use of Java 8's new features.

With Java 8 you can use method references and chained comparators, like this:

Collections.sort(persons, Comparator.comparing(Person::getFname)

.thenComparingInt(Person::getAge));

This will compare two Person instances first by their fname and - if that is equal - by their age (with a slight optimization to thenComparingInt to avoid boxing).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值