Java 集合搜索 Max Age



我需要从将他们的名字、第二个名字和年龄存储在一个元素中的集合中获取最大年龄。例:

collection[size++] = new Person(fname,lname,age);
//ex: Person("Bob", "Jones", 50);

到目前为止,我得到的代码是遍历集合,但我坚持如何获取元素的年龄部分。

public int maxAge() {
    int mAge = -1;
    for (int i = 0; i == collection.size(); i++) {
        if (collection[i] > mAge) {
            collection[i] = mAge;
        }
    }
    return mAge; 
}

getSize()获取集合大小。

假设您有一个ArrayPerson上有一个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; i < collection.length; i++) {
        if (collection[i].getAge() > mAge) {
            mAge = collection[i].getAge();
        }
    }
    return mAge; 
}

它取决于集合中对象的类型,假设是 Person 的集合:

public int maxAge() {

int mAge = -1;
for (Person person: collection) {
    if (person.getAge() > mAge) {
        mAge=person.getAge();
    }
}
return mAge; 

}

请注意您的代码。它将 mAge 分配给集合,即 -1 将被分配给集合,并且您返回的值将始终为 -1 的 mAge。

 public int maxAge() {
    int mAge = -1;
    for (int i = 0; i < getSize(); i++) {
     if (collection[i].getAge() > mAge) {
        mAge = collection[i].getAge();
      }
  }
   return mAge; 
 }

要获取具有最大年龄的 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;
    }
});

然后int maxAge = personWithMaxAge.getAge();

如果您使用的是Java8:

Optional<Person> person = collection.stream().max(Comparator.comparing(Person::getAge));

键入是可选的,因为集合可能为空。

现在您可以通过以下方式使用它:

person.ifPresent(p -> {
    // place your code here
    // System.out.println(p.getAge());
});

最新更新