'How can I list enum values and concatenate id in Java
I have an enum like this:
public enum DocumentType {
A,
B,
C,
D;
}
I want a list like this:
1 A
2 B
3 C
4 D
Solution 1:[1]
public class EnumId {
public enum DocumentType {
A(1), B(2), C(3), D(4);
final int id;
DocumentType(int id) {
this.id = id;
}
int getId() {
return this.id;
}
}
public static void main(String[] args) {
for (DocumentType dt : DocumentType.values())
System.out.println(dt.getId() + " " + dt.name());
}
}
$ javac EnumId.java
$ java EnumId
1 A
2 B
3 C
4 D
$
Solution 2:[2]
You can even use ordinal & name methods available in Enum; this don't need you to modify anything in existing DocumentType :
for(DocumentType e:DocumentType.values()) {
System.out.println((e.ordinal()+1)+" "+e.name());
}
Output:
1 A
2 B
3 C
4 D
Solution 3:[3]
Since you want to return this in a response you could do something like this:
public String yourEndpoit() {
final DocumentType[] values = DocumentType.values();
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.length; i++) {
builder.append(i)
.append(" ")
.append(values[i])
.append(System.lineSeparator());
}
return builder.toString();
}
Solution 4:[4]
A solution that leverages method declarations within enumerated types:
public enum DocumentType {
A, B, C, D;
public String asListItem() {
return String.format("%d %s", ordinal()+1, name());
}
public static String toList() {
return Arrays.stream(values())
.map(DocumentType::asListItem)
.collect(Collectors.joining("\n"));
}
}
To get the list: DocumentType.toList().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ashish Patil |
| Solution 3 | Dino PraĊĦo |
| Solution 4 | SDJ |
