public class EmptyStringEliminationWithDashJoin
1: //EmptyStringEliminationWithDashJoin.java
3: import java.util.Arrays;
4: import java.util.List;
5: import java.util.stream.Collectors;
7: public class EmptyStringEliminationWithDashJoin
8: {
9: public static void main(String args[])
10: {
11: //We will combine non-empty strings from the following list of
12: //strings into a single string with the parts separated by a dash:
13: List<String> strings
14: = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl", "mno");
15: System.out.println("\nList of strings: " + strings);
17: System.out.println("\n=============");
18: System.out.println("Using Java 7: ");
19: StringBuilder stringBuilder = new StringBuilder();
20: for (String string : strings)
21: {
22: if (!string.isEmpty())
23: {
24: stringBuilder.append(string);
25: stringBuilder.append("-");
26: }
27: }
28: String mergedString = stringBuilder.toString();
29: System.out.println
30: (
31: "Single string formed by combining all "
32: + "non-empty\nstrings, separated by a single dash:\n"
33: + mergedString.substring(0, mergedString.length() - 1)
34: );
36: System.out.println("\n=============");
37: System.out.println("Using Java 8: ");
38: System.out.println
39: (
40: "Single string formed by combining all "
41: + "non-empty\nstrings, separated by a single dash:\n"
42: + strings
43: .stream()
44: .filter(string -> !string.isEmpty())
45: .collect(Collectors.joining("-"))
46: );
47: }
48: }
49: /* Output:
51: List of strings: [abc, , bc, efg, abcd, , jkl, mno]
53: =============
54: Using Java 7:
55: Single string formed by combining all non-empty
56: strings, separated by a single dash:
57: abc-bc-efg-abcd-jkl-mno
59: =============
60: Using Java 8:
61: Single string formed by combining all non-empty
62: strings, separated by a single dash:
63: abc-bc-efg-abcd-jkl-mno
64: */