问题
I have a stream of strings:
Stream<String> stream = ...;
I want to create a string using
stream.collect(Collectors.joining(',', '[', ']'))
only I want to return "No Strings" if the stream does not contain any elements.
I notice that String java.util.stream.Stream.collect(Collector<? super String, ?, String> collector)
method takes an argument of type java.util.stream.Collector
For my project I need to this functionality in many places so I would need a class the implements the Collector
interface.
I know this could be done by Stream to a List and then checking on List.size() == 0? and then convert the list to a stream again if needed.
List<String> list = stream.collect(Collectors.toList());
if (list.size() == 0) {
return "No Strings";
}
return list.stream().collect(Collectors.joining(',', '[', ']'));`
This is what I would like to happen
List emptyList = new ArrayList<String>;
System.out.println(emptyList.steam().collect(Collectors.joining(',', '[', ']')));
Output
[,]
Output I would like
No Strings
回答1:
Honestly, I would go with your current approach (testing for emptiness).
But if you really wanted to use a straight collector, you could use the source code of Collections.joining and the Javadoc of StringJoiner as a guide to make a custom collector:
Collector.of(
() -> new StringJoiner(",", "[", "]").setEmptyValue("No strings"),
StringJoiner::add,
StringJoiner::merge,
StringJoiner::toString)
回答2:
I would also recommend using the if
statement you already have. To generate the String after that you can also use String.join()
:
List<String> list = stream.collect(Collectors.toList());
if (list.isEmpty()) {
return "No Strings";
}
return "[" + String.join(",", list) + "]";
If you do not want the if you also can use an Optional
to prevent that:
return Optional.of(stream.collect(Collectors.toList()))
.filter(l -> !l.isEmpty())
.map(l -> "[" + String.join(",", l) + "]")
.orElse("No Strings");
But I don't think this is more readable.
来源:https://stackoverflow.com/questions/56560842/custom-collector-to-join-stream-on-delimiter-suffix-and-prefix-only-if-stream-i