StreamArrayListProcessing.java
|
1 /*
2 *A program to perform some basic operations on a list of Strings
3 * using java Streams
4 */
5
6 package arraylists;
7
8 import java.util.ArrayList;
9 import java.util.List;
10 import java.util.stream.Collectors;
11
12 public class StreamArrayListProcessing {
13
14 public static void main(String[] args){
15 //POINT A: Add some strings which represent names to an ArrayList
16 List<String> names = new ArrayList<>();
17 names.add("Holiday, Billie");
18 names.add("Claudel, Camille");
19 names.add("Picasso, Pablo");
20 names.add("Gallen-Kallela, Akseli");
21 names.add("Zotto, Osvaldo");
22 names.add("Dogg, Snoop");
23 names.add("E, Big");
24
25 //POINT B: Use map and the toList collector to create an ArrayList
26 // of just the first names of the names ArrayList
27 List<String> firstNamesList = names.stream()
28 .map(n -> firstName(n))
29 .collect(Collectors.toList());
30
31 System.out.print("First Names: ");
32 for (String firstName : firstNamesList){
33 System.out.print(firstName + " ");
34 }
35 System.out.println();
36
37 //POINT C:
38 String firstNames = names.stream()
39 .map(n -> firstName(n))
40 .collect(Collectors.joining(", "));
41 System.out.println("First Names: " + firstNames);
42
43 //POINT D:
44 String lastNames = names.stream()
45 .map(n -> lastName(n))
46 .collect(Collectors.joining(", "));
47 System.out.println("Last Names: " + lastNames);
48
49 //POINT E:
50 String uppercaseFirstNames = names.stream()
51 .map(n -> firstName(n))
52 .map(n -> n.toUpperCase())
53 .collect(Collectors.joining(", "));
54 System.out.println("Uppercase First Names: " + uppercaseFirstNames);
55 //POINT F:
56 String hyphenatedLastNames = names.stream()
57 .map(n -> lastName(n))
58 .filter(n -> n.contains("-"))
59 .collect(Collectors.joining(", "));
60 //POINT G:
61 int totalLength = names.stream()
62 .map(n -> n.length())
63 .reduce(0,(n1, n2) -> n1 + n2);
64 System.out.println("Total Length: " + totalLength);
65
66 //POINT H:
67 int firstNameLength = names.stream()
68 .map(n -> firstName(n))
69 .map(n -> n.length())
70 .reduce(0,(n1, n2)-> n1 + n2);
71 System.out.println("First Name Length: " + firstNameLength);
72 //POINT I:
73 int productNameLength = names.stream()
74 .map(n -> n.length())
75 .reduce(1,(n1, n2) -> n1 * n2);
76 System.out.println("Product of Names: " + productNameLength);
77 }
78
79 private static String firstName(String name) {
80 int first = name.indexOf(",");
81 String f = name.substring(first + 2);
82 return f;
83 }
84
85 private static String lastName(String name) {
86 int last = name.indexOf(",");
87 name = name.substring(0, last);
88 return name;
89 }
90 }
91