Java集合搜索最大年龄
我需要从一个集合中获取最大年龄,该集合将他们的名字、第二个名字和年龄存储在一个元素中。 例如: 到目前为止,我得到的代码是对集合进行迭代,但我一直在研究如何获取元素的年龄部分Java集合搜索最大年龄,java,collections,iteration,Java,Collections,Iteration,我需要从一个集合中获取最大年龄,该集合将他们的名字、第二个名字和年龄存储在一个元素中。 例如: 到目前为止,我得到的代码是对集合进行迭代,但我一直在研究如何获取元素的年龄部分 public int maxAge() { int mAge = -1; for (int i = 0; i == collection.size(); i++) { if (collection[i] > mAge) { collection[i] = mAg
public int maxAge() {
int mAge = -1;
for (int i = 0; i == collection.size(); i++) {
if (collection[i] > mAge) {
collection[i] = mAge;
}
}
return mAge;
}
getSize()
获取集合大小。请注意您的代码。它将法师分配给集合,即-1将被分配给集合,并且您将返回值始终为-1的法师
public int maxAge() {
int mAge = -1;
for (int i = 0; i < getSize(); i++) {
if (collection[i].getAge() > mAge) {
mAge = collection[i].getAge();
}
}
return mAge;
}
public int maxAge(){
int-mAge=-1;
对于(int i=0;imAge){
mAge=collection[i].getAge();
}
}
返回法师;
}
假设您在Person
上有一个带有getAge()
方法的数组,您可以尝试以下操作:
public int maxAge() {
int mAge = -1;
for (int i = 0; i < collection.length; i++) {
if (collection[i].getAge() > mAge) {
mAge = collection[i].getAge();
}
}
return mAge;
}
public int maxAge(){
int-mAge=-1;
for(int i=0;imAge){
mAge=collection[i].getAge();
}
}
返回法师;
}
public int maxAge(){
int-mAge=-1;
for(int i=0;imAge){
mAge=collection[i].getAge();
}
}
返回法师;
}
它取决于集合中对象的类型,假设是人员集合:
公共整数maxAge(){
}要获取具有最大年龄的person元素:
Person personWithMaxAge = Collections.max( collection, new Comparator<Person>() {
@Override
public int compare( Person first, Person second) {
if ( first.getAge() > second.getAge() )
return 1;
else if (first.getAge() < second.getAge() )
return -1;
return 0;
}
});
Person personWithMaxAge=Collections.max(collection,newcomparator(){
@凌驾
公共整数比较(第一人,第二人){
if(first.getAge()>second.getAge())
返回1;
else if(first.getAge()
然后int-maxAge=personWithMaxAge.getAge()代码>如果您使用的是Java8:
Optional<Person> person = collection.stream().max(Comparator.comparing(Person::getAge));
作为旁注,循环中的条件将使其永不循环。要回答您的问题,请调用一个方法collection[i].getAge()
或直接访问类成员变量collection[i].age
它是什么类型的集合?@elia显然是一个数组。现在它很清楚了,但是collection.size()
将不起作用。您为什么需要假定它是一个数组?这是一个整数数组。不根据collection[size++]=新人(fname,lname,age)代码>
int mAge = -1;
for (Person person: collection) {
if (person.getAge() > mAge) {
mAge=person.getAge();
}
}
return mAge;
Person personWithMaxAge = Collections.max( collection, new Comparator<Person>() {
@Override
public int compare( Person first, Person second) {
if ( first.getAge() > second.getAge() )
return 1;
else if (first.getAge() < second.getAge() )
return -1;
return 0;
}
});
Optional<Person> person = collection.stream().max(Comparator.comparing(Person::getAge));
person.ifPresent(p -> {
// place your code here
// System.out.println(p.getAge());
});