StreamArrayListProcessing.java
|
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: Add some strings which represent names to an ArrayList
List<String> names = new ArrayList<>();
names.add("Holiday, Billie");
names.add("Claudel, Camille");
names.add("Picasso, Pablo");
names.add("Gallen-Kallela, Akseli");
names.add("Zotto, Osvaldo");
//Point B: Make an array list of the first names
List<String> firstNamesList=names.stream()
.map(n->firstName(n))
.collect(Collectors.toList());
System.out.println("First names: ");
for (String firstName: firstNamesList){
System.out.print(firstName+" ");
}
System.out.println();
//Point C: Do the same as Point B but separate each name with a comma and don't use a for loop to print the names
String firstNames=names.stream()
.map(n->firstName(n))
.collect(Collectors.joining(", "));
System.out.println("First Names: "+firstNames);
//Point D: Make an array list of the last names like in Point B with the lastName method and make a comma separated list of the names
List<String> lastNamesList=names.stream()
.map(n->lastName(n))
.collect(Collectors.toList());
String lastNames=names.stream()
.map(n->lastName(n))
.collect(Collectors.joining(", "));
System.out.println("Last Names: "+lastNames);
//Point E: Print a comma separated list of all the uppercased first names from the list of names
String firstNamesUpperCaseList=names.stream()
.map(n->firstName(n))
.map(n->n.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println("Uppercase first names: "+firstNamesUpperCaseList);
//Point F: Print a comma separated list of all the hyphenated last names
String hyphenatedLastNamesList=names.stream()
.map(n->lastName(n))
.filter(n->n.contains("-"))
.collect(Collectors.joining(", "));
System.out.println("Hypenated last names: "+ hyphenatedLastNamesList);
//Point G: print the integer value of the total length of the names list
int totalLength=names.stream()
.map(n->n.length())
.reduce(0,(n1,n2)->n1+n2);
System.out.println("Total names list length: "+ totalLength);
//Point H: print the integer value of the total length of the first names list
totalLength=firstNamesList.stream()
.map(n->n.length())
.reduce(0,(n1,n2)->n1+n2);
System.out.println("Total first names list length: "+ totalLength);
//Point I: print an integer value of the product of the names lengths in the first names list
int product=firstNamesList.stream()
.map(n->n.length())
.reduce(1,(n1, n2)->n1*n2);
System.out.println("Total first names list product: "+ product);
}
private static String lastName(String n) {
int commaPosition=n.indexOf(",");
String lastName=n.substring(0, commaPosition);
return lastName;
}
private static String firstName(String n) {
int commaPosition = n.indexOf(",");
String firstName = n.substring(commaPosition + 2, n.length());
return firstName;
}
}