问题描述
我是Java 8的新手,我只想按名称排序.但条件是:如果名称重复,则应根据年龄对其进行排序.
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.
例如,我的输入是
tarun 28
arun 29
varun 12
arun 22
,输出应为
arun 22
arun 29
tarun 28
varun 12
但是我得到类似
varun 12
arun 22
tarun 28
arun 29
表示仅按年龄或姓名排序.
Means it's sorted either only by ages or names.
这是实现的代码:
POJO类:
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;
}
}
测试类:
public class Test {
public static void main(String[] args) {
List<Person> 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<Person>() {
@Override
public int compare(Person t, Person t1) {
return t.getAge() - t1.getAge();
}
});
System.out.println(persons);
}
}
推荐答案
当前,您是a)仅按一个属性进行比较,b)并未真正利用Java 8的新功能.
Currently you are a) only comparing by one attribute and b) not really making use of Java 8's new features.
在Java 8中,您可以使用方法引用并进行链接比较器,例如:
With Java 8 you can use method references and chained comparators, like this:
Collections.sort(persons, Comparator.comparing(Person::getFname)
.thenComparingInt(Person::getAge));
这将首先通过其fname
比较两个Person
实例,如果相等,则通过其age
比较(对 thenComparingInt
以避免装箱).
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).
这篇关于如何在Java中对名称和年龄进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!