public class CountingStringsOfLength3
1: //CountingStringsOfLength3.java
3: import java.util.Arrays;
4: import java.util.List;
6: public class CountingStringsOfLength3
7: {
8: public static void main(String args[])
9: {
10: //We will count the strings of length 3 in the following
11: //list of strings:
12: List<String> strings
13: = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl", "mno");
14: System.out.println("\nList of strings: " + strings);
16: System.out.println("\n=============");
17: System.out.println("Using Java 7: ");
18: int count = 0;
19: for (String string : strings)
20: {
21: if (string.length() == 3)
22: {
23: count++;
24: }
25: }
26: System.out.println("Number of strings of length 3: " + count);
28: System.out.println("\n=============");
29: System.out.println("Using Java 8: ");
30: System.out.println
31: (
32: "Number of strings of length 3: " + strings
33: .stream()
34: .filter(string -> string.length() == 3)
35: .count()
36: );
37: }
38: }
39: /* Output:
41: List of strings: [abc, , bc, efg, abcd, , jkl, mno]
43: =============
44: Using Java 7:
45: Number of strings of length 3: 4
47: =============
48: Using Java 8:
49: Number of strings of length 3: 4
50: */