Skip to content

Instantly share code, notes, and snippets.

@bhudgeons
Last active August 29, 2015 14:06
Show Gist options
  • Save bhudgeons/79a24757d4f2617485f6 to your computer and use it in GitHub Desktop.
Save bhudgeons/79a24757d4f2617485f6 to your computer and use it in GitHub Desktop.
Java Stream "Monad" LOL
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Stream;
public class StreamTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Stream<Integer> stream = list.stream();
list.add(4);
// Haha -- this doesn't work.
// Java can't figure out that Integers are ints
// System.out.println(stream.sum());
System.out.println(stream.mapToInt(x -> x).sum());
// 10!!
System.out.println(stream.mapToInt(x -> x).sum());
//Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
// at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
// at java.util.stream.IntPipeline.<init>(IntPipeline.java:91)
// at java.util.stream.IntPipeline$StatelessOp.<init>(IntPipeline.java:592)
// at java.util.stream.ReferencePipeline$4.<init>(ReferencePipeline.java:204)
// at java.util.stream.ReferencePipeline.mapToInt(ReferencePipeline.java:203)
// at StreamTest.main(StreamTest.java:23)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment