Introduction to Data Aggregation Methods in Java

Welcome to today's lesson! Our topic for the day is data aggregation, a crucial aspect of data analysis. Like summarizing a massive book into key points, data aggregation summarizes large amounts of data into important highlights.

By the end of this lesson, you'll be equipped with several aggregation methods to summarize data streams in Java. Let's get started!

Basic Aggregation using Built-in Functions

Let's say we have a list of integers denoting the ages of a group of people:

List<Integer> ages = Arrays.asList(21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22);

Common questions we might ask are: How many people are in the group? What's their total age? Who's the youngest and the oldest? Java's handy Stream API methods like count(), mapToInt().sum(), min(), and max() have our answers:

long numPeople = ages.stream().count(); // Number of people (12)
int totalAges = ages.stream().mapToInt(Integer::intValue).sum(); // Total age (276)
int youngestAge = ages.stream().min(Integer::compareTo).orElseThrow(); // Youngest age (20)
int oldestAge = ages.stream().max(Integer::compareTo).orElseThrow(); // Oldest age (27)

// Use mapToInt().average() to find the average age
double averageAge = ages.stream().mapToInt(Integer::intValue).average().orElseThrow(); // Result: 23

// Use max() and min() to find the range of ages
int ageRange = ages.stream().max(Integer::compareTo).orElseThrow() - ages.stream().min(Integer::compareTo).orElseThrow(); // Result: 7

These functions provide essential aggregation operations and are widely used with data streams.

Advanced Aggregation using For and While Loops

For deeper analyses, such as calculating the average age or range of ages manually, we can use for loops.

For example, using for loops, we can also find the mode or most frequent age:

List<Integer> ages = Arrays.asList(21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22);

// Initialize a map to store the frequency of each age
Map<Integer, Integer> frequencies = new HashMap<>();

// Use a for loop to populate frequencies
for (int age : ages) {
    frequencies.put(age, frequencies.getOrDefault(age, 0) + 1);
}

// Find the age with the max frequency
int maxFreq = 0;
int modeAge = -1;
for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
    if (entry.getValue() > maxFreq) {
        maxFreq = entry.getValue();
        modeAge = entry.getKey();
    }
}
System.out.println("Max frequency: " + maxFreq); // Max frequency: 4
System.out.println("Mode age: " + modeAge); // Mode age: 22

While loops can also be used similarly for more complex tasks.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal