有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java集合搜索最大年龄

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

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()获取集合大小


共 (6) 个答案

  1. # 1 楼答案

    请注意你的密码。它将法师分配给集合,即-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; 
     }
    
  2. # 2 楼答案

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

  3. # 3 楼答案

    它取决于集合中对象的类型,假设为人员集合:

    public int maxAge(){

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

    }

  4. # 4 楼答案

    如果您使用的是Java8:

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

    该类型是可选的,因为集合可能为空

    现在您可以这样使用它:

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

    假设在Person上有一个带有getAge()方法的Array,您可以尝试以下方法:

    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; 
    }
    
  6. # 6 楼答案

    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; 
    }