Course contentsShow
← Java
Lesson 1588 of 2,87034. Collectors in DepthFree lesson

Understanding summingInt, summingLong, and summingDouble

Explore the summing collectors that calculate the sum of extracted numeric values from stream elements.

Understanding summingInt, summingLong, and summingDouble

You'll learn how to sum numeric values extracted from stream elements using specialized summing collectors.

The Core Idea

While counting() tells you how many elements exist, the summingInt(), summingLong(), and summingDouble() collectors answer a different question: what is the total of a particular numeric property across all elements? These collectors extract a numeric value from each stream element using a mapping function, then calculate the sum of those values.

Think of it like a cashier tallying up a shopping cart. Instead of counting items (that's counting()), you're adding up their prices to get the total bill.

How They Work

Each summing collector takes a function that extracts the value to sum:

List<String> words = List.of("cat", "elephant", "dog", "bird");

// Sum the lengths of all strings
int totalLength = words.stream()
    .collect(Collectors.summingInt(String::length));
// Result: 3 + 8 + 3 + 4 = 18

The three variants handle different numeric types:

  • summingInt(ToIntFunction) – for int values
  • summingLong(ToLongFunction) – for long values
  • summingDouble(ToDoubleFunction) – for double values

Choosing the Right Collector

Use the collector that matches your data type. For whole numbers that fit in an int, use summingInt(). For larger whole numbers or when dealing with long fields, use summingLong(). For decimal values or when precision matters, use summingDouble().

// If you have prices as doubles
List<Double> prices = List.of(19.99, 5.50, 12.75);
double total = prices.stream()
    .collect(Collectors.summingDouble(price -> price));

Key Takeaway: Use summingInt(), summingLong(), or summingDouble() to calculate the sum of numeric values extracted from stream elements, choosing the collector that matches your data type.