4

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
userit1985
  • 961
  • 1
  • 13
  • 28
  • Does this answer your question? [Java: convert List to a String](https://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-string) – luk2302 Jan 08 '20 at 09:26
  • Does this answer your question? [Getting all names in an enum as a String\[\]](https://stackoverflow.com/questions/13783295/getting-all-names-in-an-enum-as-a-string) – Julien Lopez Jan 08 '20 at 10:52

4 Answers4

10

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
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
6

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"
w08r
  • 1,639
  • 13
  • 14
  • Answers should not be just code, please provide a summary of what this is actually doing so other users can understand what is happening. – Popeye Jan 09 '20 at 09:22
  • Much better, it just helps others understand what your code does that's all; can be especially helpful to those just starting out +1 – Popeye Jan 09 '20 at 09:29
0

I think you have to somehow invoke the toString() method of your enum Levels, maybe by means of HashSet.stream() like this:

public static void main(String[] args) {
    Set<Level> levels = new HashSet<>(Arrays.asList(Level.LOW, Level.HIGH));
    List<String> levelStrings = levels.stream()
                                    .map(Level::toString)
                                    .collect(Collectors.toList());
    String result = String.join(", ", levelStrings);
    System.out.println(result);
}

Output:

LOW, HIGH
deHaar
  • 17,687
  • 10
  • 38
  • 51
0

You can do like this:

Set<LevelsEnum> levels = new HashSet<>(Arrays.asList(LevelsEnum.LOW, LevelsEnum.HIGH));

String result = levels.stream()
        .map(LevelsEnum::toString)
        .collect(Collectors.joining(","));
System.out.println(result);
Popeye
  • 11,839
  • 9
  • 58
  • 91
Ankur Gupta
  • 312
  • 1
  • 3