1

I'm new to java and I'm having a problem with ArrayList. I want to get the highest value from Jozef and Klaus.

ArrayList looks like:

|  Name        | Age|
+--------------+----+
| Jozef Coin   | 55 |    
| Jozef Coin   | 56 |    
| Jozef Coin   | 57 |
| Klaus Neumer | 34 |
| Klaus Neumer | 31 |
| Klaus Neumer | 59 |

This is my code so far, it only returns the highest value in the arraylist.

Person b = persons.get(0)

for(Person p: persons){    
      if(p.getAge() >= b.getAge()){    
         b = p;    
           System.out.println(b.toString());    
      }    
}

I'm probably way over my head but I'd love to know if this is possible and if so there is an solution to this.

3
  • 1
    Could you please clarify your question? What does the Person class look like? Commented Apr 3, 2016 at 4:57
  • 1
    So instead of highest in the list you want highest for each person? Commented Apr 3, 2016 at 5:00
  • Yes exactly Sam Orozco. Commented Apr 3, 2016 at 5:02

4 Answers 4

3

You can use Comparable for your task

public class CompareAge implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getAge().compareTo(p2.getAge());
    }
}

Then use that CompareAge class like as follows

Collections.sort(myArrayList, new CompareAge());
myArrayList.get(arrayList.size() - 1); //Retrieve the last object
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was a great solution to the problem.
0

It's hard to answer unless we know the methods in the Person class, however this would be the general way I would do it.

Person b = persons.get(0)
int jozefHighest = 0;
int klausHighest = 0;

for(Person p: persons){

      if(p.getName().startsWith("Jozef") {
        if(p.getAge() > jozefHighest)
            jozefHighest = p.getAge)_
      } else if (p.getName().startsWith("Klaus")) {
        if(p.getAge() > klausHighest)
            klausHighest = p.getAge()
      }

}

Comments

0

Java 8 is Cool!

    int[] a = {1,2,3,4};
    OptionalInt maxValue = IntStream.of(a).max();
    System.out.println("Max Value: " + maxValue);

Comments

0

You can do this in a single step in Java 8:

Map<String, Integer> oldestMap = persons.stream()
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.maxBy(Person::getAge).get());

You now have a map from name to maximum age.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.