Skip to content

Commit 0b04d65

Browse files
committed
Added Collection vs Stream
1 parent 0fec070 commit 0b04d65

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ This repository contains the basic &amp; 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

0 commit comments

Comments
 (0)