LINQ and the Stream API: C# and Java
A query over a list is the task both languages solved: C# with LINQ, whose operators are methods and whose query syntax is a second spelling of them; Java with the Stream API, which arrived in Java 8 and is the same idea built from Stream and Collector. The task is four orders grouped by customer, a filter, a sum and an average.
The task in C#
The orders are a record with a customer and an amount in decimal. The report is one chain: group, project, sort, then print; the filter and the aggregates follow:
Console.WriteLine("linq 1.0");
var orders = new[]
{
new Order("ada", 120.50m),
new Order("bob", 80m),
new Order("ada", 30m),
new Order("cy", 200m),
};
var totals = orders
.GroupBy(order => order.Customer)
.Select(group => new { Customer = group.Key, Total = group.Sum(order => order.Amount) })
.OrderBy(row => row.Customer)
.ToList();
foreach (var row in totals)
{
Console.WriteLine($"{row.Customer,-6}{row.Total,8:F2}");
}
var big = orders.Where(order => order.Amount >= 100m).Select(order => order.Customer);
Console.WriteLine($"over 100: {string.Join(", ", big)}");
Console.WriteLine($"sum {orders.Sum(order => order.Amount):F2}");
Console.WriteLine($"average {orders.Average(order => order.Amount):F2}");
record Order(string Customer, decimal Amount);
dotnet run
echo "status: $?"
linq 1.0
ada 150.50
bob 80.00
cy 200.00
over 100: ada, cy
sum 430.50
average 107.63
status: 0
The same task in Java
The same four orders as a record with a double amount. The grouping is a collector into a TreeMap, which sorts the keys, and the filter and the aggregates are three more streams:
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class LinqStreams {
record Order(String customer, double amount) {
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("ada", 120.50),
new Order("bob", 80),
new Order("ada", 30),
new Order("cy", 200));
System.out.println("linq 1.0");
Map<String, Double> totals = orders.stream()
.collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingDouble(Order::amount)));
for (var entry : totals.entrySet()) {
System.out.printf("%-6s%8.2f%n", entry.getKey(), entry.getValue());
}
String big = orders.stream()
.filter(order -> order.amount() >= 100)
.map(Order::customer)
.collect(Collectors.joining(", "));
System.out.println("over 100: " + big);
System.out.println("sum " + String.format("%.2f", orders.stream().mapToDouble(Order::amount).sum()));
System.out.println("average " + String.format("%.2f", orders.stream().mapToDouble(Order::amount).average().orElse(0)));
}
}
javac -g -d out LinqStreams.java
java -cp out LinqStreams
echo "status: $?"
linq 1.0
ada 150.50
bob 80.00
cy 200.00
over 100: ada, cy
sum 430.50
average 107.63
status: 0
What differs
- The output is the same, line for line, which is why the page can put the two blocks next to each other. The machinery is not: a C# query is a chain of extension methods on IEnumerable, and a Java stream is a pipeline with a terminal operation that runs it.
- The sort of the groups is explicit in C# (OrderBy(row => row.Customer)) and a choice of collector in Java (TreeMap::new). A HashMap would print the groups in another order.
- C# has a second syntax for the same operators: the query form with from, where and select, which compiles to the method calls of the page. Java has one form.
- The amount type is a real difference. C# sums a decimal exactly; Java sums a double and formats the result with %.2f, so two amounts that should be 0.1 apart can differ in the last bit. A money program in Java uses BigDecimal.
- A stream is single use in Java: a second terminal operation on the same stream throws IllegalStateException. A LINQ query is a value that can be enumerated again, which lesson 037 of the C# course measures with a captured variable.
The next page is about time: three waits that overlap, in tasks and in futures.
Exercises
- Write the grouped report of the C# page in query syntax and compare it with the method chain.
- Change the Java collector to a HashMap and print the group order.
- Add a fifth order and check that both sums move by the same amount.
- Use BigDecimal in Java and decimal in C# for the amounts and compare the printed totals.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a Java stream?
Answer
A pipeline of operations with one terminal operation that runs it
The page runs one pipeline per aggregate.
-
Which collector groups the orders in Java?
Answer
Collectors.groupingBy
The measured line uses groupingBy with a TreeMap and a summingDouble.
-
What does this program print?
var values = new[] { 1, 2, 3 }; Console.WriteLine(values.Where(v => v > 0).Sum());Answer
6
The C# sum of the same chain is the measured answer.
-
What does a second terminal operation on a Java stream do?
Answer
It throws IllegalStateException
A stream is single use, unlike a LINQ query.
-
What does this program print?
var orders = new[] { ("ada", 120m), ("bob", 80m) }; Console.WriteLine(orders.First(o => o.Item2 >= 100).Item1);Answer
ada
The first customer over a hundred is ada in the measured output.
-
Why does the C# page sort with OrderBy?
Answer
The order of a grouping is not promised, and the report must be stable
The Java page makes the same choice with TreeMap.
-
What does this program print?
var orders = new[] { ("ada", 120.50m), ("ada", 30m) }; Console.WriteLine($"{orders.Sum(o => o.Item2):F2}");Answer
150.50
Two orders of the same customer add to the measured line.
-
Which type keeps money exact in Java?
Answer
BigDecimal
The page names BigDecimal as the Java answer to decimal.
-
What does this program print?
var amounts = new[] { 120.5, 80, 30, 200 }; Console.WriteLine(amounts.Count(a => a >= 100));Answer
2
Two orders of the measured list are over a hundred.
-
What does a LINQ query return before it is enumerated?
Answer
A sequence that runs the chain when enumerated
Deferred execution is the subject of lesson 037 of the C# course.
The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.
Article author: Arthur Isaev