Java-从arraylist打印字符串
如何从arraylist打印字符串?为此,可以使用java 8:Java-从arraylist打印字符串,java,Java,如何从arraylist打印字符串?为此,可以使用java 8: Optional <Person> shortestPersonOpt = people.stream().min(Comparator.comparingDouble(Person::getHeight)); 跟踪人,而不是高度的值 Person smallest = null; for (Person person : People) { if (smallest == null || person.getH
Optional <Person> shortestPersonOpt = people.stream().min(Comparator.comparingDouble(Person::getHeight));
跟踪人,而不是高度的值
Person smallest = null;
for (Person person : People) {
if (smallest == null || person.getHeight() < smallest.getHeight()) {
smallest = person;
}
}
Person=null;
用于(人:人){
if(minimate==null | | person.getHeight()
//如果列表中没有人或值最小的人,则“最小”现在为空。要查找最短的人,因此您可以使用该人的其他信息,您需要记住该人,而不仅仅是该人的身高,如下所示:
person shortest = null;
for (person p : People) {
if (shortest == null || p.getHeight() < shortest.getHeight()) {
shortest = p;
}
}
String s = shortest.toString();
person-shortest=null;
用于(人员p:人员){
if(shortest==null | | p.getHeight()
当然,您可能需要检查
People
是否为空,否则当您尝试调用toString()
FYI时,您将得到一个NullPointerException
:您的命名被颠倒了。Java命名约定是,类名以大写字母开头,变量名以小写字母开头,因此Person
和people
将是命名事物的正常方式。您正在保存(最短)高度,但不保存具有该高度的人。您希望记住最矮的人,然后打印该人的toString()
。参见Andreas的回答。这是因为代码缺少一个片段,即comparingDouble
部分:可选的shortestPersonOpt=People.stream().min(Comparator.comparingDouble(person::getHeight))代码>@Andreas感谢您的编辑!我只是直接写的,忘记了比较器。请解释你的答案,以及它是如何解决这个问题的。
person shortest = null;
for (person p : People) {
if (shortest == null || p.getHeight() < shortest.getHeight()) {
shortest = p;
}
}
String s = shortest.toString();