If you don't need an intermediate list and just want to join String
other way around:
String delimiter = "."; Optional<String> result = Pattern.compile("/") .splitAsStream(str) .filter(s -> ! s.isEmpty()) .reduce((s, s2) -> String.join(delimiter, s2, s));
Or just use .reduce((s1, s2) -> s2 + '.' + s1);
, since it probably reads as String.join(".", s2, s1);
(thanks to Holger for the suggestion).
From now on, you can do one of the following:
result.ifPresent(System.out::println); // print the result String resultAsString = result.orElse(""); // get the value or default to empty string resultAsString = result.orElseThrow(() -> new RuntimeException("not a valid path?")); // get the value or throw an exception
Another way to use StreamSupport
and Spliterator
(inspired by Mishas' suggestion to use Path
):
Optional<String> result = StreamSupport.stream(Paths.get(str).spliterator(), false) .map(Path::getFileName) .map(Path::toString) .reduce((s, s2) -> s2 + '.' + s);
Of course, you can simplify it by omitting the intermediate Optional
object and immediately name your desired method:
stream(get(str).spliterator(), false) .map(Path::getFileName) .map(Path::toString) .reduce((s, s2) -> s2 + '.' + s) .ifPresent(out::println);
in the last example, you would add the following static import:
import static java.lang.System.out; import static java.nio.file.Paths.get; import static java.util.stream.StreamSupport.stream;