The following text was written to the standard output stream when the StreamArrayListProcessing program was executed from IntelliJ.
/*
*A program to perform some basic operations on a list of Strings
* using java streams.
*/
package arraylistplay;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamArrayListProcessing {
public static void main(String[] args){
//Point a
List names = new ArrayList<>();
names.add("Holiday, Billie");
names.add("Claudel, Camille");
names.add("Picasso, Pablo");
names.add("Gallen-Kallela, Akseli");
names.add("Zotto, Osvaldo");
List firstNamesList = names.stream()
.map(n -> firstName(n))
.collect(Collectors.toList());
System.out.print("First names: ");
for (String firstName : firstNamesList){
System.out.print(firstName + " ");
}
System.out.println();
//Point c
String firstNames = names.stream()
.map(n -> firstName(n))
.collect(Collectors.joining(", "));
System.out.println("First names: " + firstNames);
//POINT D
List lastNamesList = names.stream()
.map(n -> lastName(n))
.collect(Collectors.toList());
System.out.print("Last names: ");
for (String lastName : lastNamesList){
System.out.print(lastName + " ");
}
System.out.println();
//Point c
String lastNames = names.stream()
.map(n -> lastName(n))
.collect(Collectors.joining(", "));
System.out.println("Last names: " + lastNames);
//Point e
String upperCaseFirstNames = names.stream()
.map(n -> firstName(n))
.map(n -> n.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println("UpperCase first names: " + upperCaseFirstNames);
//POINT F
String hyphenatedLastNames = names.stream()
.map(n -> lastName(n))
.filter(n -> n.contains("-"))
.collect(Collectors.joining(", "));
System.out.println("Hyphenated Last names: " + hyphenatedLastNames);
//POINT G
int totalLength = names.stream()
.map(n -> n.length())
.reduce(0, (n1, n2) -> n1 + n2);
System.out.println("Total length: " + totalLength);
//POINT H
int totalLengthFirstNames = names.stream()
.map(n -> firstName(n))
.map(n -> n.length())
.reduce(0, (n1, n2) -> n1 + n2);
System.out.println("First name length: " + totalLengthFirstNames);
//POINT I
int totalLengthOfNamesProduct = names.stream()
.map(n -> n.length())
.reduce(1, (n1, n2) -> n1 * n2);
System.out.println("Product of names: " + totalLengthOfNamesProduct);
}
private static String firstName(String directoryStyleName) {
int positionOfComma = directoryStyleName.indexOf(",");
String firstName = directoryStyleName.substring(positionOfComma + 2);
return firstName;
}
private static String lastName(String directoryStyleName) {
int positionOfComma = directoryStyleName.indexOf(",");
String lastName = directoryStyleName.substring(0, positionOfComma);
return lastName;
}
}