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?
Here is one possible version (Java 8+)
enum Levels {
LOW, MEDIUM, HIGH;
}
...
String s = EnumSet.allOf(Levels.class).stream().map(Enum::toString).collect(Collectors.joining(","));
// EnumSet.of(Levels.LOW, Levels.HIGH) if you want some specific enums
System.out.println(s);
The result is:
LOW,MEDIUM,HIGH
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With