ArrayList consists of objects, each of which has a temperature and time.
It is necessary to find the maximum temperature for each day.
So far it turns out to find just the maximum temperature value as follows:

 for (int i = 1; i < history.size(); i++) { if (history.get(0).getCelsius() > max && history.get(0).getDate().equals(history.get(i).getDate())) { max = history.get(0).getCelsius(); } } 

I am trying to figure out how to write it better, but nothing happens. Maybe there are some tips / tips. I understand that it is necessary to determine that history.get(i).getDate() should not be equal to history.get(i).getDate() with the same value, but I don’t know how to do it.

    3 answers 3

    I got this solution:

     histories .stream() .collect( //группируем по дате, отбрасывая время Collectors.groupingBy(e -> DateTimeFormatter.ISO_LOCAL_DATE.format(e.getDate()), //выбираем максимальный элемент на основе температуры Collectors.maxBy((e1, e2) -> (int) (e1.getCelsius() - e2.getCelsius())))) //выводим результат .forEach((date, history) -> System.out.println(date + " - " + history.map(History::getCelsius).get())); 

    where:

     List<History> histories = new ArrayList<>(); 

    And History has the following structure:

     @Data private static class History { LocalDateTime date; double celsius; } 
    • works great! thank! - Alex

    Create a Hashmap , where the key is the day, and the value is the maximum degree. In each iteration you are looking for whether there is this day in the map; if not, add both day and degree. If the day was already in the map, simply compare the values ​​of the degrees and, if necessary, rest

    • Now I will try to study. then I will need to convert arraylist to hashmap - Alex
    • 2
      @Alex do not need to convert. create a separate Map. then move on your list and add to the Map. - Mikhail Vaysman

    As an alternative solution in Java 8:

     Map<Date, Double> result = history.stream().collect(Collectors.toMap(HeatSensor::getDate, HeatSensor::getCelsius, (a, b) -> a == null ? b : Math.max(a, b)));