Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to convert Enum values into comma seperated String

Tags:

java

string

enums

I have a java class in which I store an Enum.(shown at the bottom of this question) In this enum, I have a method named toCommaSeperatedString() who returns a comma separated String of the enums values. I am using a StringBuilder after reading some information on performance in this question here.

Is the way I am converting this enum's values into a commaSeperatedString the most efficient way of doing so, and if so, what would be the most efficient way to remove the extra comma at the last char of the String?

For example, my method returns 123, 456, however I would prefer 123, 456. If I wanted to return PROPERTY1, PROPERTY2 I could easily use Apache Commons library StringUtils.join(), however, I need to get one level lower by calling the getValue method when I am iterating through the String array.

public class TypeEnum {
    public enum validTypes {
        PROPERTY1("123"),
        PROPERTY2("456");

        private String value;

        validTypes(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static boolean contains(String type) {
            for (validTypes msgType : validTypes.values()) {
                if (msgType.value.equals(type)) {
                    return true;
                }
            }
            return false;
        }

        public static String toCommaSeperatedString() {
            StringBuilder commaSeperatedValidMsgTypes = new StringBuilder();
            for(validTypes msgType : validTypes.values()) {
                commaSeperatedValidMsgTypes.append(msgType.getValue() + ", ");
            }
            return commaSeperatedValidMsgTypes.toString();
        }
    }
}
like image 671
DevelopingDeveloper Avatar asked Feb 03 '26 16:02

DevelopingDeveloper


1 Answers

I wouldn't worry much about efficiency. It's simple enough to do this that it will be fast, provided you don't do it in a crazy way. If this is the most significant performance bottleneck in your code, I would be amazed.

I'd do it something like this:

return Arrays.stream(TypeEnum.values())
      .map(t -> t.value)
      .collect(Collectors.joining(','));

Cache it if you want; but that's probably not going to make a huge difference.

like image 130
Andy Turner Avatar answered Feb 05 '26 05:02

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!