how to print all enum value in java?

System.out.println(java.util.Arrays.asList(generalInformation.values()));

Your second part... Just the same as an interface or a class


Firstly, I would refactor your enum to pass the string representation in a constructor parameter. That code is at the bottom.

Now, to print all enum values you'd just use something like:

// Note: enum name changed to comply with Java naming conventions
for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {
    System.out.println(info);
}

An alternative to using EnumSet would be to use GeneralInformation.values(), but that means you have to create a new array each time you call it, which feels wasteful to me. Admittedly calling EnumSet.allOf requires a new object each time too... if you're doing this a lot and are concerned about the performance, you could always cache it somewhere.

You can use GeneralInformation just like any other type when it comes to parameters:

public void doSomething(GeneralInformation info) {
    // Whatever
}

Called with a value, e.g.

doSomething(GeneralInformation.PHONE);

Refactoring using a constructor parameter

public enum GeneralInformation {
    NAME("Name"),
    EDUCATION("Education"),
    EMAIL("Email"),
    PROFESSION("Profession"),
    PHONE("Phone");

    private final String textRepresentation;

    private GeneralInformation(String textRepresentation) {
        this.textRepresentation = textRepresentation;
    }

    @Override public String toString() {
         return textRepresentation;
    }
}

With your current values, you could actually just convert the name to title case automatically - but that wouldn't be very flexible for the long term, and I think this explicit version is simpler.


Since Java 8 I would suggest the following solution:

public static String printAll() {
    return Stream.of(GeneralInformation.values()).
                map(GeneralInformation::name).
                collect(Collectors.joining(", "));
}

Tags:

Java