Last active
August 29, 2015 14:01
-
-
Save jeremychone/8573504fc6c5d6a87489 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<String> names = Arrays.asList("one","two ","three"); | |
// fancy builtin collector with delimiter | |
String s = names.stream().collect(Collectors.joining(", ")); | |
System.out.println(s); | |
// "one, two , three" | |
// name elements does not get trimmed, so, need custom. | |
// Let's see how we can get there with the custom collector collect(supplier,accumulator,multiplier) | |
// custom collector using method references (without delimiter) | |
StringBuilder sb = names.stream().collect(StringBuilder::new, // supplier | |
StringBuilder::append, // accumulator | |
StringBuilder::append); // multiplier | |
System.out.println(sb.toString()); | |
// "onetwo three" | |
// Exact same as above using lambdas (without delimiter) | |
sb = names.stream().collect(() -> {return new StringBuilder();}, // supplier | |
(sb1,name) -> {sb1.append(name);}, // accumulator | |
(sb1,sb2) -> {sb1.append(sb2);}); // multiplier | |
System.out.println(sb.toString()); | |
// "onetwo three" | |
// Exac collector using lambdas with the delimiter logic. | |
final String delim = ", "; | |
sb = names.stream().collect(() -> {return new StringBuilder();}, // supplier | |
(sb1,name) -> { // accumulator | |
if (sb1.length() > 0){ | |
sb1.append(delim); | |
} | |
sb1.append(name); | |
}, | |
(sb1,sb2) -> {sb1.append(sb2);}); // multiplier | |
System.out.println(sb.toString()); | |
// "one, two , three" | |
// trim and lambda only as needed (only accumulator needs to have custom logic) | |
sb = names.stream().collect(StringBuilder::new, // supplier | |
(sb1,name) -> { // accumulator | |
if (sb1.length() > 0){ | |
sb1.append(delim); | |
} | |
sb1.append(name.trim()); | |
}, | |
StringBuilder::append); // multiplier | |
System.out.println(sb.toString()); | |
// "one, two, three" | |
// Conclusion: | |
// + Stream.collect API it much simpler than it looks, and very flexible. | |
// + Use builtin collector when possible. | |
// + Do not be afraid to do you custom collector. | |
// + Most of the time, custom code is just necessary on the accumulator. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment