Java convert enum list to string list

Most convenient way to convert enumeration values to string array in Java

And I want to convert this to a string array with minimal effort and no loops with Java 8+. This is the best I came up with:

Arrays.stream(Weather.values()).map(Enum::toString).toArray(String[]::new) 

@christopher-schneider: I can. But that is not the point. My point is to create a minimal conversion, does not matter where it is.

2 Answers 2

Original post

Yes, that’s a good Java 8 way, but.

The toString can be overridden, so you’d better go with Weather::name which returns the name of an enum constant (exactly as declared in the enum declaration) and can’t be changed:

Stream.of(Weather.values()).map(Weather::name).toArray(String[]::new); 

A bit of generics

I wrote a helper class to deal with any enum in a generic way:

class EnumUtils < public static > String[] getStringValues(Class enumClass) < return getStringValuesWithStringExtractor(enumClass, Enum::name); >public static > String[] getStringValuesWithStringExtractor( Class enumClass, Function extractor ) < return of(enumClass.getEnumConstants()).map(extractor).toArray(String[]::new); >> 
enum Weather < RAINY, SUNNY, STORMY; @Override public String toString() < return String.valueOf(hashCode()); >public static void main(String[] args) < System.out.println(Arrays.toString(EnumUtils.getStringValues(Weather.class))); System.out.println(Arrays.toString(EnumUtils.getStringValuesWithStringExtractor(Weather.class, Weather::toString))); >> 
[RAINY, SUNNY, STORMY] [359023572, 305808283, 2111991224] 

Источник

Convert Enum list to comma separated String with matching Enum value

I have a List of Enum values like MON, TUE, WED, etc., same need to convert to comma-separated String. Need to use Java 8 to convert the same in an efficient way. For example.

Arrays.stream(Days.values()) .map(MON -> TimeRangeConstants.MON) .collect(Collectors.joining(",")); 
enum Days < MON, TUE, WED, THU, FRI, SAT, SUN; >main() < Days v1 = Days.MON; Days v2 = Days.WED; Days v3 = Days.FRI; Listdays = new ArrayList<>(); days.add(v1); days.add(v2); days.add(v3); String str = convertToString(days); > convertToString(List list) < // need to return String as "Monday, Wednesday, Friday" >

Because income request is having enum values and by framework converting to List which I don’t have control on that to change. But in the service layer, I need to change List into String with comma separated values.

Читайте также:  Java sql server client

2 Answers 2

You would have to edit the enum to:

enum Days < MON("Monday"), TUE("Tuesday"), WED("Wednesday") ; private String val; Days(String val) < this.val = val; >@Override public String toString() < return val; >> 

If you have access to the newer stream() method, you can do this:

final String s = String.join(",", list.stream().map(Object::toString).collect(Collectors.toList()); System.out.println("s mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Aug 5, 2019 at 16:52
1
    Thanks, kailoon :) got my solution
    – Anandnld
    Aug 5, 2019 at 16:58
Add a comment|
2

You can declare a new method in the enum to map the day to the name of the day and then use the java-8 streams like this:

import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class DaysToCsv < enum Days < MON, TUE, WED, THU, FRI, SAT, SUN; public static String getFullName(Days day) < switch (day) < case MON: return "Monday"; case TUE: return "Tuesday"; case WED: return "Wednesday"; case THU: return "Thursday"; case FRI: return "Friday"; case SAT: return "Saturday"; case SUN: return "Sunday"; default: throw new IllegalArgumentException("Unexpected day"); >> > public static void main(String[] args) < Days v1 = Days.MON; Days v2 = Days.WED; Days v3 = Days.FRI; Listdays = new ArrayList<>(); days.add(v1); days.add(v2); days.add(v3); String str = convertToString(days); System.out.println(str); > public static String convertToString(List list) < return list.stream().map(day ->Days.getFullName(day)).collect(Collectors.joining(", ")); > >

Источник

Converting ArrayList of enums to String

The problem is, that arrayListToString is called with ArrayList and cannot be called with ArrayList parameter (which is the type of my classes). I also cannot create a class with type Enum . Since enum != Enum , how do I make arrayListToString method work with my enum classes?

Note that enum values are effectively constants, and according to the Java Naming Conventions, they should be written in UPPER_SNAKE_CASE. Also, you can leave out those empty constructors, since they're automatically created when you specify no other constructor.

Thank you. I didn't know that about the empty constructors. I am familiar with the naming conventions of Java, it's just that in my case, my server will expect Pascal Cased parameters. That's why the enums are named like that.

3 Answers 3

Since an enum X is implicitly a subclass of Enum , change method declaration to:

public static String arrayListToString(ArrayList arrayList) 

The toString() of a enum returns the name() by default, so you don't need to call name() , which means you don't really care what's in the list anymore, so this much more generally useful method will work too:

public static String listToString(List list) < StringBuilder buf = new StringBuilder(); boolean first = true; for (Object value : list) < if (first) first = false; else buf.append(", "); buf.append(value); >return buf.toString(); > 

It can be even simpler than that:

public static String toString(Iterable iterable)
public static String toString(Collection coll)

Change the signature of arrayListToString() from this:

public static String arrayListToString(ArrayList arrayList) 
public static String arrayListToString(ArrayList arrayList) 

The core concept at play is that a List is not a List , even though an Integer is a Number . This makes sense, because you could put a Double into a List but you could not put a Double into a List .

Similarly, a List is not a List , even though a RewardType is an Enum .

A List is, though, a List . This is because we now are saying that the list is a list of some sort of enum, not a list of any enum ever.

Источник

Polymorphically convert Java enum values into a list of strings

I have a handful of helper methods that convert enum values into a list of strings suitable for display by an HTML

/** * Gets the list of available colours. * * @return the list of available colours */ public static List getColours() < Listcolours = new ArrayList(); for (Colour colour : Colour.values()) < colours.add(colour.getDisplayValue()); >return colours; > 

I'm still pretty new to Java generics, so I'm not sure how to pass a generic enum to the method and have that used within the for loop as well. Note that I know that the enums in question will all have that getDisplayValue method, but unfortunately they don't share a common type that defines it (and I can't introduce one), so I guess that will have to be accessed reflectively. Thanks in advance for any help.

10 Answers 10

static > List toStringList(Class clz) < try < Listres = new LinkedList(); Method getDisplayValue = clz.getMethod("getDisplayValue"); for (Object e : clz.getEnumConstants()) < res.add((String) getDisplayValue.invoke(e)); >return res; > catch (Exception ex) < throw new RuntimeException(ex); >> 

this is not completely typesafe since you can have an Enum without a getDisplayValue method.

If it's a heavily used method and/or you have a lot of Enums, then you may want to consider having that array calculated once as a static during class initialization rather than recreating it every time.

You changed his ArrayList to a LinkedList. AFAIU, the difference is that the first has higher performance in random lookup, while the second has higher performance in random insert or delete. Since his list is originally an enumeration, he will (likely) need to lookup the list at random indexes. so wouldn't ArrayList perform faster?

I would add the methodName string parameter to this method so this could be used for any of the methods of the Enum.

You can stick this method in some utility class:

public static > List getDisplayValues(Class enumClass) < try < T[] items = enumClass.getEnumConstants(); Method accessor = enumClass.getMethod("getDisplayValue"); ArrayListnames = new ArrayList(items.length); for (T item : items) names.add(accessor.invoke(item).toString())); return names; > catch (NoSuchMethodException ex) < // Didn't actually implement getDisplayValue(). >catch (InvocationTargetException ex) < // getDisplayValue() threw an exception. >> 

There are two things you can do here. The first (simpler, and therefore better) way would just be to have your getStrings() method take a list of some interface, and make your enums implement that interface:

public interface DisplayableSelection < public String getDisplayValue(); >private static List getStrings (Collection things) < Listretval = new ArrayList(); for (DisplayableSelection thing : things) < retval.add(thing.getDisplayValue()); >> private static List getColours ()

If you really care internally that the type is an Enum, you can also use the fact that all enumerated types automatically subclass the built-in type Enum. So, for your example (disclaimer: I think this compiles, but haven't actually tried it):

public interface DisplayableEnum < public String getDisplayValue(); >private static & DisplayableEnum > List getDisplayValues(Class pClass) < Listretval = new ArrayList(); for (DisplayableSelection thing : pClass.getEnumConstants()) < retval.add(thing.getDisplayValue()); >> private static List getColours ()

This second form can be useful if you want to do something that specifically requires an enumeration (e.g. use an EnumMap or EnumSet for some reason); otherwise, I'd go with the first (since with that method, you can also use non-enumerated types, or just a subset of the enumeration).

Источник

Оцените статью