Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java concatenate List of enum to String

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?

like image 888
userit1985 Avatar asked Sep 17 '25 07:09

userit1985


2 Answers

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
like image 131
Mark Bramnik Avatar answered Sep 19 '25 15:09

Mark Bramnik


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"
like image 21
w08r Avatar answered Sep 19 '25 13:09

w08r