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