Search⌘ K
AI Features

Solution: The Cargo Load Balancer

Explore how to implement a cargo load balancer by applying functional programming in Java. Learn to use Streams for filtering null and empty containers, mapping weights to moments, and reducing sums for stability calculation.

We'll cover the following...
Java 25
import java.util.List;
import java.util.Arrays;
public class LoadBalancer {
public record Container(String id, double weight, double position) {}
public static double calculateStabilityScore(List<Container> manifest) {
return manifest.stream()
// 1. Filter out nulls first to avoid NullPointerException
.filter(c -> c != null)
// 2. Filter out empty containers
.filter(c -> c.weight() != 0)
// 3. Map to Moment (Weight * Position)
.map(c -> c.weight() * c.position())
// 4. Reduce to a single sum
.reduce(0.0, (total, moment) -> total + moment);
}
public static void main(String[] args) {
List<Container> manifest = Arrays.asList(
new Container("C-101", 5000.0, 10.0), // Moment: 50,000
null, // Error
new Container("C-102", 2000.0, -5.0), // Moment: -10,000
new Container("C-103", 0.0, 20.0), // Empty
new Container("C-104", 4000.0, 5.0) // Moment: 20,000
);
double totalScore = calculateStabilityScore(manifest);
System.out.println("Total Stability Score: " + totalScore);
}
}
...