如何获取具有最小属性的列表元素?
我编写这段代码是为了找到最年轻的人:
import java.util.Comparator;
import java.util.List;
public class PersonImpl implements PersonInterface {
@Override
public Person youngest(List<Person> personList) {
Integer minAge = personList.stream()
.map(Person::getAge)
.min(Comparator.comparing(Integer::valueOf))
.orElse(null);
return personList.stream()
.filter(person -> person.getAge() == minAge)
.toList()
.stream()
.findFirst()
.orElse(null);
}
}
如您所见,我做到了并且工作正常。现在我想知道我是否可以以更好的方式做到这一点(也许不是用 2 个“语句”只完成一个?) PS:我只提供了代码,因为我认为不需要在这里发布所有其他类只是为了回顾这个类。
有人可以解释一下如何才能拥有更好的代码(更少的行)吗? 谢谢
I write this code to find the youngest person:
import java.util.Comparator;
import java.util.List;
public class PersonImpl implements PersonInterface {
@Override
public Person youngest(List<Person> personList) {
Integer minAge = personList.stream()
.map(Person::getAge)
.min(Comparator.comparing(Integer::valueOf))
.orElse(null);
return personList.stream()
.filter(person -> person.getAge() == minAge)
.toList()
.stream()
.findFirst()
.orElse(null);
}
}
As you can see I did it and is working correctly . Now I want to know if I can do this in a better way (maybe instead of having 2 "statements" to go done to only one?)
PS: I provided only the code since I assume that there is no need to post all the other classes in here just to review this one only.
Can someone explain me what can be done to have a better code(less lines)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需删除
map()
并让您的比较器对Person
进行年龄查找:如果您知道列表非空,最好通过调用 < code>get() 或
orElseThrow()
而不是orElse()
。或者,您可以使用Collections
帮助器代替流:顺便说一下,当您已经拥有流时,调用
.toList().stream()
是完全没有意义的。对Integer
调用Integer::valueOf
也是没有意义的。Just cut out the
map()
and have your comparator do the age lookup onPerson
:If you know the list is non-empty, better to make that explicit by calling
get()
ororElseThrow()
instead oforElse()
. Or you can use theCollections
helper instead of streams:By the way, calling
.toList().stream()
when you already have a stream is completely pointless. There's also no point in callingInteger::valueOf
on anInteger
.不要
绘制
年龄。不必仅仅为了查找结构内整数的最小值而进行析构。Don't
map
out the ages. It is not necessary to destruct just for finding the minimun value of an integer inside the struct.