Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
How to find the max element from an array list of objects?

Collections.max(arraylist) doesn't work, and a regular for loop won't work either.

What I have is:

ArrayList<Forecast> forecasts = current.getForecasts();

Collections.max(forecast) gives me this error:

The method max(Collection<? extends T>) in the type Collections is
not applicable for the arguments (ArrayList<Forecast>)

The ArrayList holds Forecast objects which each has an int field for the temperature of each day. I am trying to store the max in an int max.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

As your ArrayList contains Forecast objects you'll need to define how the max method should find the maximum element within your ArrayList.

something along the lines of this should work:

ArrayList<Forecast> forecasts = new ArrayList<>();
// Forecast object which has highest temperature
Forecast element = Collections.max(forecasts, Comparator.comparingInt(Forecast::getTemperature));
// retrieve the maximum temperature
int maxTemperature = element.getTemperature();
over 4 years ago · Santiago Trujillo Relatório

0

Another solution is use map reduce:

Optional<Forecast> element = forecasts
                     .stream()
                     .reduce((a,b) -> a.getTemperature() > b.getTemperature() ? a : b );

In this way you could even use use parallelStream()

over 4 years ago · Santiago Trujillo Relatório

0

Streams are perfect for these sort of problems.

Forecast highest = forecasts.stream()
                            .max((fc1, fc2) -> fc1.getTemp() - fc2.getTemp())
                            .get();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda