StreamArrayListProcessing.java
|
1 /*
2 * A program to perform some basic operations on a list of Strings
3 * using Java streams.
4 */
5 package arraylistplay;
6
7 import java.util.ArrayList;
8 import java.util.List;
9 import java.util.stream.Collectors;
10
11 public class StreamArrayListProcessing {
12 public static void main(String[] arg) {
13
14 //Point A:
15 List<String> names = new ArrayList<>();
16 names.add("Holiday, Billie");
17 names.add("Squarepants, Spongebob");
18 names.add("Brady, Tom");
19 names.add("Saget, Bob");
20 names.add("Joe, Billy-Bob");
21 names.add("Green, Nathan");
22
23
24 //Point B:
25 List<String> firstNamesList = names.stream()
26 .map(n -> firstName(n))
27 .collect(Collectors.toList());
28 System.out.println("First names: ");
29 for (String firstName : firstNamesList){
30 System.out.println(firstName + " ");
31 }System.out.println();
32
33 //Point C:
34 String firstNames = names.stream()
35 .map(n -> firstName(n))
36 .collect(Collectors.joining(", "));
37 System.out.println("First names: " + firstNames);
38 System.out.println();
39
40 //Point D:
41 List<String> lastNamesList = names.stream()
42 .map(n -> lastName(n))
43 .collect(Collectors.toList());
44 System.out.println("Last names: ");
45 for (String lastName : lastNamesList){
46 System.out.println(lastName + " ");
47 }System.out.println();
48
49 String lastNames = names.stream()
50 .map(n -> lastName(n))
51 .collect(Collectors.joining(", "));
52 System.out.println("Last names: " + lastNames);
53
54 //Point E:
55 String upperCaseFirstNames = names.stream()
56 .map(n -> firstName(n))
57 .map(n -> n.toUpperCase())
58 .collect(Collectors.joining(", "));
59 System.out.println("Uppercase first names: " + upperCaseFirstNames);
60
61 //Point F:
62 String hyphenatedLastNames = names.stream()
63 .map(n -> lastName(n))
64 .filter(n -> n.contains("-"))
65 .collect(Collectors.joining(", "));
66 System.out.println("hyphenateds names: " + hyphenatedLastNames);
67
68 //Point G:
69 int totalLength = names.stream()
70 .map(n -> n.length())
71 .reduce(0, (n1, n2) -> n1 + n2);
72 System.out.println("Total length: " + totalLength);
73
74 //Point H:
75 int totalfirstLength = names.stream()
76 .map(n -> n.length())
77 .reduce(0, (n1, n2) -> n1 + n2);
78 System.out.println("first name Total length: " + totalfirstLength);
79
80 //Point I:
81 double totalProduct= names.stream()
82 .map(n-> n.length())
83 .reduce(1,(n1,n2)-> n1 * n2);
84 System.out.println("Total Product:"+ totalProduct);
85 }
86
87 private static String firstName(String directoryStyleName) {
88 int commaPosition = directoryStyleName.indexOf(",");
89 return directoryStyleName.substring(commaPosition + 2);
90 }
91 private static String lastName(String directoryStyleName) {
92 int commaPosition = directoryStyleName.indexOf(",");
93 return directoryStyleName.substring(0, commaPosition);
94 }
95 }