StreamArrayListProcessing.java
|
1 /*
2 * A program to perform some basic operations on a lost of Strings using Java streams.
3 */
4
5 package arraylists;
6
7 import java.util.ArrayList;
8 import java.util.List;
9 import java.util.stream.Collectors;
10
11 public class StreamArrayListProcessing {
12
13 public static void main(String[] args){
14 List<String> names = new ArrayList<>();
15 names.add("Holiday, Billie");
16 names.add("Claudel, Camille");
17 names.add("Picasso, Pablo");
18 names.add("Gallen-Kallela, Akseli");
19 names.add("Zotto, Osvaldo");
20 names.add("Randall, Damian");
21 names.add("Struempfler, Emily");
22
23 //
24 List<String> firstNamesList = names.stream()
25 .map(n -> firstName(n))
26 .collect(Collectors.toList());
27
28 System.out.print("First names: ");
29 for (String firstName : firstNamesList){
30 System.out.print(firstName + " ");
31 }
32 System.out.println();
33 //
34
35 //
36 String firstNames = names.stream()
37 .map(n-> firstName(n))
38 .collect(Collectors.joining(", "));
39
40 System.out.println("First names: " + firstNames);
41 //
42
43 //
44 List<String> lastNamesList = names.stream()
45 .map(n -> lastName(n))
46 .collect(Collectors.toList());
47
48 String lastNames = names.stream()
49 .map(n-> lastName(n))
50 .collect(Collectors.joining(", "));
51
52 System.out.println("Last names: " + lastNames);
53 //
54
55 //
56 String upperCaseFirstNames = names.stream()
57 .map(n -> firstName(n))
58 .map(n -> n.toUpperCase())
59 .collect(Collectors.joining(", "));
60 System.out.println("Uppercase first names: " + upperCaseFirstNames);
61 //
62
63 //
64 String hyphenatedLastNames = names.stream()
65 .map(n -> lastName(n))
66 .filter(n -> n.contains("-"))
67 .collect(Collectors.joining(", "));
68 System.out.println("Hyphenated last names: " + hyphenatedLastNames);
69 //
70
71 //
72 int totalLength = names.stream()
73 .map(n -> n.length())
74 .reduce(0, (n1, n2) -> n1 + n2);
75 System.out.println("Total length: " + totalLength);
76
77 int firstTotalLength = names.stream()
78 .map(n -> n.length())
79 .reduce(0, (n1, n2) -> n1 + n2);
80 System.out.println("First name total length: " + firstTotalLength);
81
82
83
84
85
86 }
87
88 private static String lastName(String directoryStyleName) {
89 int directoryStyleNameCommaPosition = directoryStyleName.indexOf(",");
90 String lastName = directoryStyleName.substring(0, directoryStyleNameCommaPosition);
91 return lastName;
92 }
93
94 private static String firstName(String directoryStyleName) {
95 int margin = 2;
96 int directoryStyleNameCommaPosition = directoryStyleName.indexOf(",");
97 String firstName = directoryStyleName.substring(directoryStyleNameCommaPosition + margin);
98 return firstName;
99 }
100 }
101