Your stream is almost ok because it returns Optional<Person>
, then you need a get()
to ensure return the Person
object, not the optional.
Or, as Alex said into comments, use orElse
to avoid exceptions.
So you can use this line into the method:
public Person bestPayed(List<Person> persons) {
return persons.stream().max(Comparator.comparingInt(Person::getSalary)).get();
}
Or using orElse
:
public Person bestPayed(List<Person> persons) {
return persons.stream().max(Comparator.comparingInt(Person::getSalary)).orElse(null);
}
Is better using orElse()
because if your list is empty, then Optional<Person>
will be empty too and trying to get()
it will throw an exception:
java.util.NoSuchElementException: No value present
Also your code fails (maybe is a typo) because you are returning Person
, and, what is Person? You have to return the result of the stream.
And to output the object you can call the method like this:
System.out.println("BestPayed = "+bestPayed(persons));
And add a toString()
method in your Person
class. This method is to output the object as an string, and depends on what attributes your class have.
For example, assuming your class has name
, surname
and salary
your toString()
could be something like this:
@Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", salary=" + salary + "]";
}
But you can add or delete what you want to output.
And running this code the console output is:
BestPayed = Person [name=Ku, surname=No, salary=5000]
Also if you only want to display the salary, use this:
System.out.println("Best salary = "+bestPayed(persons).getSalary());