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.

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
Ilja
  • 85
  • 1
  • 7

4 Answers4

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
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
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()
      }

}
Austin
  • 4,801
  • 6
  • 34
  • 54
0

Java 8 is Cool!

    int[] a = {1,2,3,4};
    OptionalInt maxValue = IntStream.of(a).max();
    System.out.println("Max Value: " + maxValue);
Suparna
  • 1,132
  • 1
  • 8
  • 20
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.

sprinter
  • 27,148
  • 6
  • 47
  • 78