Created
April 29, 2018 22:45
-
-
Save neshkeev/f9a1f8d320abaef951bf28d29768fbb5 to your computer and use it in GitHub Desktop.
Join a list of strings using `java.util.Optional`
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
import java.util.*; | |
import java.util.function.*; | |
import java.util.stream.*; | |
public final class Joiner { | |
public final static Optional<String> join(final String delimiter, final List<String> input) { | |
final BiConsumer<StringBuilder, String> appender = | |
(acc, next) -> { | |
if (acc.length() == 0) acc.append(next); | |
else acc.append(delimiter).append(next); | |
}; | |
final Collector<String, StringBuilder, String> clctr = | |
Collector.of( | |
StringBuilder::new, | |
appender, | |
StringBuilder::append, | |
StringBuilder::toString | |
); | |
final Function<List<String>, String> toStr = e -> e.stream().collect(clctr); | |
return Optional.ofNullable(input).map(toStr); | |
} | |
public static void main(String []args){ | |
final List<String> empty = Collections.EMPTY_LIST; | |
final List<String> single = Collections.singletonList("value"); | |
final List<String> list = new ArrayList<String>(){{ | |
add("value1"); | |
add("value2"); | |
add("value3"); | |
}}; | |
System.out.println("Join null: " + join(", ", null)); | |
System.out.println("Join an empty list: " + join(", ", null)); | |
System.out.println("Join a single element list: " + join(", ", single)); | |
System.out.println("Join a list of values: " + join(", ", list)); | |
} | |
} | |
/* | |
$java -Xmx128M -Xms16M Joiner | |
Join null: Optional.empty | |
Join an empty list: Optional.empty | |
Join a single element list: Optional[value] | |
Join a list of values: Optional[value1, value2, value3] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment