Stream confusion
Archie Cobbs
archie.cobbs at gmail.com
Wed Nov 22 16:06:48 UTC 2023
I have an API design question about Streams, but instead of asking the
question outright I thought I'd ask it indirectly with a simple example.
The Javadoc for Stream opens with this example:
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
OK, looks reasonable - we're computing the sum of the weights of all the
red widgets.
Here's the question: Is the following program deterministic?
import java.awt.*;
import java.util.function.*;
import java.util.stream.*;
import static java.awt.Color.*;
public class Widget {
private final Color color;
private final int weight;
public Widget(Color color, int weight) {
this.color = color;
this.weight = weight;
}
public Color getColor() {
return this.color;
}
public int getWeight() {
return this.weight;
}
public static int totalRedWeight(Widget... widgets) {
return Stream.of(widgets)
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
}
// Test method
public static void main(String[] args) {
final Widget w1 = new Widget(RED, 123);
final Widget w2 = new Widget(BLUE, 456);
final int total = Widget.totalRedWeight(w1, w2);
System.out.println("Total red weight = " + total);
}
}
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231122/c053c21a/attachment.htm>
More information about the amber-dev
mailing list