LearnFrenzy
Sign in Take a free test

Streams API · Streams API Programs · Question 8

Temperature readings: partition, stats and streaks in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

For a month of daily temperatures, print summary statistics, partition the days into hot (≥ 35) and normal, list the hot day numbers, and find the longest run of hot days.

Solution
Main.java
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        double[] t = {31.5, 33.0, 35.2, 36.8, 37.1, 34.0, 32.2, 35.5, 36.0, 33.9, 30.8, 35.0, 35.9, 36.4, 37.8, 34.1};
        DoubleSummaryStatistics s = java.util.Arrays.stream(t).summaryStatistics();
        System.out.printf("min %.1f max %.1f avg %.2f%n", s.getMin(), s.getMax(), s.getAverage());

        Map<Boolean, Long> split = IntStream.range(0, t.length).boxed().collect(Collectors.partitioningBy(i -> t[i] >= 35, Collectors.counting()));
        List<Integer> hotDays = IntStream.range(0, t.length).filter(i -> t[i] >= 35).map(i -> i + 1).boxed().toList();
        System.out.println("hot " + split.get(true) + ", normal " + split.get(false) + ", hot days " + hotDays);

        int best = 0, run = 0;
        for (double d : t) { run = d >= 35 ? run + 1 : 0; best = Math.max(best, run); }
        System.out.println("longest heatwave " + best + " days");
    }
}

Output Verified by compiling and running

min 30.8 max 37.8 avg 34.70
hot 9, normal 7, hot days [3, 4, 5, 8, 9, 12, 13, 14, 15]
longest heatwave 4 days

Streaming over indexes keeps the day numbers; a simple loop is still the clearest way to find a run – streams are not the answer to everything.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links