public class StringExample
1: //StringExample.java
2:
3: import java.util.ArrayList;
4: import java.util.Arrays;
5: import static java.lang.System.out;
6:
7: public class StringExample
8: {
9: public static void main(String[] args)
10: {
11: String[] a = {"Robert", "Ali", "Salvatore", "Hans"};
12: ArrayList<String> names = new ArrayList<>(Arrays.asList(a));
13: out.println("\nHere are the names:");
14: for (String name : names) out.print(name + " ");
15: out.println();
16:
17: //Find the average name length (number of characters):
18: double averageLength = names.stream()
19: .mapToInt(name -> name.length())
20: .average()
21: .getAsDouble();
22: out.printf("The average length of the names is %1.1f "
23: + "characters.", averageLength);
24:
25: //Find the longest name:
26: String longestName = names.stream()
27: .reduce("", (name1, name2) ->
28: {
29: return name1.length() > name2.length() ? name1 : name2;
30: }
31: );
32: out.printf("\nThe longest name is %s.\n\n", longestName);
33: }
34: }
35: