File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
Modern-Java-Examples/src/com/learn/streams Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .learn .streams ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .stream .Stream ;
5+
6+ public class CollectionVsStream {
7+
8+ public static void main (String [] args ) {
9+
10+ /**
11+ * <p>
12+ * In Collection, we can add, remove or modify the Values.
13+ * </p>
14+ */
15+ ArrayList <String > names = new ArrayList <>();
16+ names .add ("adam" );
17+ names .add ("jim" );
18+ names .add ("jenny" );
19+
20+ names .remove (0 );
21+ System .out .println (names );
22+
23+ /**
24+ * <p>
25+ * But Stream, doesn't allow us to add, modify or delete elements once it is created.
26+ * </p>
27+ */
28+
29+ /**
30+ * <p>
31+ * Collections can be traversed "n" times.
32+ * </p>
33+ */
34+ for (String name : names ) {
35+ System .out .println (name );
36+ }
37+
38+ for (String name : names ) {
39+ System .out .println (name );
40+ }
41+
42+ /**
43+ * Streams can be traversed only once
44+ */
45+ Stream <String > namesStream = names .stream ();
46+
47+ namesStream .forEach (System .out ::println );
48+ namesStream .forEach (System .out ::println ); // it throws an Exception. stream has already been operated upon or closed.
49+
50+ }
51+ }
Original file line number Diff line number Diff line change @@ -23,6 +23,7 @@ This repository contains the basic & advance level examples related to Java
2323 * [ Lambdas and Local Variables] ( Modern-Java-Examples/src/com/learn/lambdas/LambdaVariable1.java )
2424 * [ Streams] ( Modern-Java-Examples/src/com/learn/streams )
2525 * [ Stream Example] ( Modern-Java-Examples/src/com/learn/streams/StreamsExample.java )
26+ * [ Collection vs Stream] ( Modern-Java-Examples/src/com/learn/streams/CollectionVsStream.java )
2627
2728
2829
You can’t perform that action at this time.
0 commit comments