-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamDemp.java
More file actions
56 lines (38 loc) · 1.54 KB
/
StreamDemp.java
File metadata and controls
56 lines (38 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.java8;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamDemp {
public static void main(String[] args) {
// create a list of integers
List<Integer> number = Arrays.asList(2, 3, 4, 5);
// demonstration of map method
List<Integer> square = number.stream().map(x -> x * x).collect(Collectors.toList());
System.out.println(square);
// create a list of String
List<String> names = Arrays.asList("Reflection", "Collection", "Stream");
// demonstration of filter method
List<String> result = names.stream().filter(s -> s.startsWith("S")).collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> show = names.stream().sorted().collect(Collectors.toList());
System.out.println(show);
// create a list of integers
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 2);
Iterator<Integer> numberItearte=numbers.iterator();
while (numberItearte.hasNext()) {
Integer n = (Integer) numberItearte.next();
}
// collect method returns a set
Set<Integer> squareSet = numbers.stream().map(x -> x * x).collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
number.stream().map(x -> x * x).forEach(y -> System.out.println(y));
// demonstration of reduce method
int even = number.stream().filter(x -> x % 2 == 0).reduce(0, (ans, i) -> ans + i);
System.out.println(even);
}
}