Having a list of enum value, I need to convert it to a single string separated by some character.
enum Level {
LOW,
MEDIUM,
HIGH
}
Set<Level> levels = new HashSet<>(Arrays.asList(Level.LOW, Level.HIGH));
The expected result :
String result = "LOW, HIGH"
Is there a String.join
for enum?
There isn't a Strings.join for enum, as such, but you can map the set of levels into Strings and then join them, for example:
levels.stream().map(Enum::toString).collect(Collectors.joining(","))
Would yield (with your original set)
jshell> enum Level {
...> LOW,
...> MEDIUM,
...> HIGH
...> }
| created enum Level
jshell> Set<Level> levels = new HashSet<>(Arrays.asList(Level.LOW, Level.HIGH));
levels ==> [LOW, HIGH]
jshell> levels.stream().map(Enum::toString).collect(Collectors.joining(","))
$3 ==> "LOW,HIGH"