-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamExamples.java
50 lines (42 loc) · 1.89 KB
/
StreamExamples.java
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
package coreservlets;
import java.util.*;
public class StreamExamples {
public static void main(String[] args) {
List<String> words =
Arrays.asList("hi", "hello", "hola", "bye", "goodbye", "adios");
System.out.printf("Original words: %s.%n", words);
// Stream<String> wordStream = words.stream(); Then, reuse wordStream. NO!! Why not?
// Question: do I need toUpperCase on s1?
// Answer: no.
String upperCaseWords =
words.stream().reduce("", (s1, s2) -> s1 + s2.toUpperCase());
System.out.printf("Single uppercase String: %s.%n",
upperCaseWords);
// Alternative solution to problem 1: change into uppercase
// at the end instead of as you go along.
String upperCaseWordsAlt =
words.stream().reduce("", String::concat).toUpperCase();
System.out.printf("Single uppercase String: %s.%n",
upperCaseWordsAlt);
String upperCaseWords2 =
words.stream().map(String::toUpperCase) // Or .map (s -> s.toUpperCase())
.reduce("", String::concat); // Or .reduce("", (s1,s2) -> s1+s2)
System.out.printf("Single uppercase String: %s.%n",
upperCaseWords2);
String wordsWithCommas =
words.stream().reduce((s1, s2) -> s1 + "," + s2)
.orElse("need at least two strings");
System.out.printf("Comma-separated String: %s.%n",
wordsWithCommas);
int numberOfChars =
words.stream().mapToInt(String::length)
.sum();
System.out.printf("Total number of characters: %s.%n",
numberOfChars);
long numberOfWordsWithH =
words.stream().filter(s -> s.contains("h"))
.count();
System.out.printf("Number of words containing 'h': %s.%n",
numberOfWordsWithH);
}
}