<div dir="ltr"><div>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.<br></div><div><br></div><div>The Javadoc for <span style="font-family:monospace">Stream</span> opens with this example:</div><div><pre><code> int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();<br></code></pre></div><div><div><span class="gmail_signature_prefix">OK, looks reasonable - we're computing the sum of the weights of all the red widgets.<br></span></div><div><span class="gmail_signature_prefix"><br></span></div><div><span class="gmail_signature_prefix">Here's the question: Is the following program deterministic?<br></span></div><div><span class="gmail_signature_prefix"><br></span></div><div style="margin-left:40px"><span style="font-family:monospace">import java.awt.*;<br>import java.util.function.*;<br>import java.util.stream.*;<br>import static java.awt.Color.*;<br><br>public class Widget {<br><br> private final Color color;<br> private final int weight;<br><br> public Widget(Color color, int weight) {<br> this.color = color;<br> this.weight = weight;<br> }<br><br> public Color getColor() {<br> return this.color;<br> }<br><br> public int getWeight() {<br> return this.weight;<br> }<br><br> public static int totalRedWeight(Widget... widgets) {<br> return Stream.of(widgets)<br> .filter(w -> w.getColor() == RED)<br> .mapToInt(w -> w.getWeight())<br> .sum();<br> }<br><br>// Test method<br><br> public static void main(String[] args) {<br> final Widget w1 = new Widget(RED, 123);<br> final Widget w2 = new Widget(BLUE, 456);<br> final int total = Widget.totalRedWeight(w1, w2);<br> System.out.println("Total red weight = " + total);<br> }<br>}</span></div><div><br></div><div>-Archie<br></div><div><span class="gmail_signature_prefix"><br></span></div><div><span class="gmail_signature_prefix">-- </span></div><div><div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature">Archie L. Cobbs<br></div></div></div></div>