How can I get the name of a Java Enum type given its value?
I have the following code which works for a particular Enum type, can I make it more generic?
public enum Category {
APPLE("3"),
ORANGE("1"),
private final String identifier;
private Category(String identifier) {
this.identifier = identifier;
}
public String toString() {
return identifier;
}
public static String getEnumNameForValue(Object value){
Category[] values = Category.values();
String enumValue = null;
for(Category eachValue : values) {
enumValue = eachValue.toString();
if (enumValue.equalsIgnoreCase(value)) {
return eachValue.name();
}
}
return enumValue;
}
}
You should replace your getEnumNameForValue by a call to the name() method.
Try below code
public enum SalaryHeadMasterEnum {
BASIC_PAY("basic pay"),
MEDICAL_ALLOWANCE("Medical Allowance");
private String name;
private SalaryHeadMasterEnum(String stringVal) {
name=stringVal;
}
public String toString(){
return name;
}
public static String getEnumByString(String code){
for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
if(e.name.equals(code)) return e.name();
}
return null;
}
}
Now you can use below code to retrieve the Enum by Value
SalaryHeadMasterEnum.getEnumByString("Basic Pay")
Use Below code to get ENUM as String
SalaryHeadMasterEnum.BASIC_PAY.name()
Use below code to get string Value for enum
SalaryHeadMasterEnum.BASIC_PAY.toString()
Try, the following code..
#Override
public String toString() {
return this.name();
}
Here is the below code, it will return the Enum name from Enum value.
public enum Test {
PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
"DivideByZero");
private String operationName;
private Test(final String operationName) {
setOperationName(operationName);
}
public String getOperationName() {
return operationName;
}
public void setOperationName(final String operationName) {
this.operationName = operationName;
}
public static Test getOperationName(final String operationName) {
for (Test oprname : Test.values()) {
if (operationName.equals(oprname.toString())) {
return oprname;
}
}
return null;
}
#Override
public String toString() {
return operationName;
}
}
public class Main {
public static void main(String[] args) {
Test test = Test.getOperationName("Plus One");
switch (test) {
case PLUS:
System.out.println("Plus.....");
break;
case MINUS:
System.out.println("Minus.....");
break;
default:
System.out.println("Nothing..");
break;
}
}
}
In such cases, you can convert the values of enum to a List and stream through it.
Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
I believe it's better to provide the required method in the enum itself. This is how I fetch Enum Name for a given value. This works for CONSTANT("value") type of enums.
public enum WalletType {
UPI("upi-paymode"),
PAYTM("paytm-paymode"),
GPAY("google-pay");
private String walletType;
WalletType(String walletType) {
this.walletType = walletType;
}
public String getWalletType() {
return walletTypeValue;
}
public WalletType getByValue(String value) {
return Arrays.stream(WalletType.values()).filter(wallet -> wallet.getWalletType().equalsIgnoreCase(value)).findFirst().get();
}
}
e.g. WalletType.getByValue("google-pay").name()
this will give you - GPAY
enum MyEnum {
ENUM_A("A"),
ENUM_B("B");
private String name;
private static final Map<String,MyEnum> unmodifiableMap;
MyEnum (String name) {
this.name = name;
}
public String getName() {
return this.name;
}
static {
Map<String,MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
for (MyEnum instance : MyEnum.values()) {
map.put(instance.getName().toLowerCase(),instance);
}
unmodifiableMap = Collections.unmodifiableMap(map);
}
public static MyEnum get (String name) {
return unmodifiableMap.get(name.toLowerCase());
}
}
Now you can use below code to retrieve the Enum by Value
MyEnum.get("A");
Related
I run the following to get Bean's fields and its values but I get the alphabetical order of property names.
Is there a way to get the order in which they can maintain the order in which bean has?
My Bean
#Component
public class FeedFile {
private String pkey;
private String omsOrderId;
private String auctTitl;
private String byrCntryId;
private String lstgCurncyIsoCodeName;
private String transSiteId;
public String getPkey() {
return pkey;
}
public void setPkey(String pkey) {
this.pkey = pkey;
}
public String getOmsOrderId() {
return omsOrderId;
}
public void setOmsOrderId(String omsOrderId) {
this.omsOrderId = omsOrderId;
}
public String getAuctTitl() {
return auctTitl;
}
public void setAuctTitl(String auctTitl) {
this.auctTitl = auctTitl;
}
public String getByrCntryId() {
return byrCntryId;
}
public void setByrCntryId(String byrCntryId) {
this.byrCntryId = byrCntryId;
}
public String getLstgCurncyIsoCodeName() {
return lstgCurncyIsoCodeName;
}
public void setLstgCurncyIsoCodeName(String lstgCurncyIsoCodeName) {
this.lstgCurncyIsoCodeName = lstgCurncyIsoCodeName;
}
public String getTransSiteId() {
return transSiteId;
}
public void setTransSiteId(String transSiteId) {
this.transSiteId = transSiteId;
}
Introspector code. Using StringBuilder to verify the order of Introspector.getBeans.getPropertyDescriptors() that returns in alphabetical order. It isn't related to hashmap random order in the result.
StringBuilder sb = new StringBuilder();
Map<String, String> result = new HashMap<>();
for (PropertyDescriptor pd : Introspector.getBeanInfo(file.getClass()).getPropertyDescriptors()) {
String name = pd.getName();
Object value = pd.getReadMethod().invoke(file);
if ("class".equals(name)) continue;
sb.append(name);
sb.append(":");
sb.append(value);
sb.append(",");
result.put(name, String.valueOf(value));
}
Actual Output of the above in String Builder sb:
sb.toString()="auctTitl:Hello,byrCntryId:123,lstgCurncyIsoCodeName:USD,omsOrderId:234,pkey:567, transSiteId:987,";
Expected Output should be in the order of declaration of above bean FeedFile:
sb.toString()="pkey:567,omsOrderId:234,auctTitl:Hello,byrCntryId:123,lstgCurncyIsoCodeName:USD,transSiteId:987,";
I googled and found that Introspector only returns in alphabetical order. Is there any way I can get the expected output.
I changed my above approach and this simplified it a lot.
I actually found a better way of doing this using PrintWriter, where my bean gets directly added to csv by overriding toString() in java bean. Here is what I did:
public void writeToCsv(List<Sample> sampleList, String header) throws IOException {
PrintWriter writer = new PrintWriter("filepath/demo/sample.csv");
writer.println(header);
for (Sample sample : sampleList) {
writer.println(sample.toString());
}
writer.close();
}
Bean
class Sample {
private String id;
private String type;
private String name;
private int value;
// getter-setter
#Override
public String toString(){
StringBuilder dataBuilder = new StringBuilder();
appendFieldValue(dataBuilder, id);
appendFieldValue(dataBuilder, type);
appendFieldValue(dataBuilder, name);
appendFieldValue(dataBuilder, value);
return dataBuilder.toString();
}
private void appendFieldValue(StringBuilder dataBuilder, String fieldValue) {
if(fieldValue != null) {
dataBuilder.append(fieldValue).append(",");
} else {
dataBuilder.append("").append(",");
}
}
}
I need something like this
public enum SolutionType {
RMS,
CPA,
BUSINESS DRIVERS,
NA
}
where BUSINESS DRIVERS is a value with space
Java forbids the use of spaces in enums.
However you could use an underscore and implement a custom toString():
public enum SolutionType {
RMS, CPA, BUSINESS_DRIVERS, NA;
#Override
public String toString() {
return this.name().replace("_", " ");
}
}
Or just add a custom field to the enum:
public enum SolutionType {
RMS, CPA, BUSINESS_DRIVERS("BUSINESS DRIVERS"), NA;
private String readableName;
private SolutionType() {
this.readableName = this.name();
}
private SolutionType(String name) {
this.readableName = name;
}
public String getReadableName() {
return this.readableName;
}
}
or a mix of the two...
public enum SolutionType {
RMS, CPA, BUSINESS_DRIVERS("BUSINESS DRIVERS"), NA;
private String readableName;
private SolutionType() {
this.readableName = this.name();
}
private SolutionType(String name) {
this.readableName = name;
}
#Override
public String toString() {
return this.readableName;
}
}
I am trying to assign the value returned by some function to a field in the deserialized class of json.
FileInfo.java
public class FileInfo {
#SerializedName("Name")
private String mName;
#SerializedName("Url")
private String mUri;
#SerializedName("Size")
private Integer mSize;
#SerializedName("ModTime")
private Long mModifiedTime;
private FileType mType;
#SerializedName("Children")
private ArrayList<FileInfo> mChildren = new ArrayList<>();
public ArrayList<FileInfo> getChildren() {
return mChildren;
}
public long getModifiedTime() {
return mModifiedTime;
}
public String getName() {
return mName;
}
public Integer getSize() {
return mSize;
}
public String getUrl() {
return mUri;
}
public FileType getType() {
return mType;
}
public void setChildren(ArrayList<FileInfo> mChildren) {
this.mChildren = mChildren;
}
public void setModifiedTime(long mModifiedTime) {
this.mModifiedTime = mModifiedTime;
}
public void setName(String mName) {
this.mName = mName;
}
public void setSize(Integer mSize) {
this.mSize = mSize;
}
public void setType(FileType mType) {
this.mType = mType;
}
public void setUri(String mUri) {
this.mUri = mUri;
}
#Override
public String toString() {
return FileInfo.class.toString();
}
public FileInfo() {
}
}
The mType needs to be assigned to foo(mName). I looked up custom deserializers and instance creators but none of those helped. I also thought of TypeAdapters which i feel defeats the purpose of keeping deserialization(using GSON) simple.
This is a sample JSON string that will be deserialized.
[
{
"Name":"Airport",
"Url":"http://192.168.2.2/api/sites/Baltimore%20Airport/Airport",
"Size":0,
"ModTime":"2015-12-02T14:19:17.29824-05:00",
"Children":null
}
]
P.S. I'm not sure if this should be done during deserialization but trying anyways. Also please let me know of alternative ways to achieve this.
This question already has answers here:
How to retrieve Enum name using the id?
(11 answers)
Closed 8 years ago.
i dont know how to effective get name of my enum type in java
I have:
public enum EventType{
event_one(1, "ONE"), event_two(2, "TWO");.........
private final int value;
private final String eventName;
private EventType(int EventType, String name) {
this.value = EventType;
this.eventName = name;
}
public String getEventName() {
return eventName;
}
public int getValue() {
return this.value;
}
}
And now, i want get eventName by id.. enum.get(1); //ONE
What is best way? For loop? Or is there any other way?
You don't really need an "id". Use enum.ordinal() instead. Then you can just do something like this:
public String getEventName(int id) { return EventType.values[id].getName(); }
You can use EventType.values()[position-1].getEventName() if your values are in order. Second approach is to use Map and get the Enum by code and retrieve event Name. Below is an example of the 2 approaches mentioned.
import java.util.HashMap;
import java.util.Map;
enum EventType {
event_one(1, "ONE"), event_two(2, "TWO");
private final int value;
private final String eventName;
private EventType(int EventType, String name) {
this.value = EventType;
this.eventName = name;
}
public String getEventName() {
return eventName;
}
public int getValue() {
return this.value;
}
static Map<Integer, EventType> map = new HashMap<>();
static {
for (EventType catalog : EventType.values()) {
map.put(catalog.value, catalog);
}
}
public static EventType getByCode(int code) {
return map.get(code);
}
public static EventType getByPosition(int positionCode) {
return EventType.values()[positionCode - 1];
}
public static void main(String[] args) {
String name = EventType.getByCode(1).getEventName();
System.out.println(EventType.getByPosition(1).getEventName());
System.out.println(name);
}
}
Output
ONE
ONE
I'm facing this task:
I have class A and class B. These two classes are different but almost the same.
I need to somehow merge them into 1 Single array of objects so I will be able to use them later in a list that combines both classes.
Class A:
public class Followers {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
Class B:
public class Following {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
I've tried doing this next move:
Object[] obj1 = (Object[]) followers;
Object[] obj2 = (Object[]) followings;
Object[] completeArray = ArrayUtils.addAll(obj1, obj2);
Where followers and followings are both arrays of the corresponding classes. Then in my list adapter I use:
if (values[currentItem] instanceof Followers) { BLA BLA BLA}
else if (values[currentItem] instanceof Following) { BLA BLA BLA}
But I get this exception:
Caused by: java.lang.ArrayStoreException: source[0] of type json.objects.Following cannot be stored in destination array of type json.objects.Followers[]
What will be the best way to merge two arrays of different objects into one array?
Will just implementing the same interface between them do the job and then they will basically be in an array of the interface type?
what other ways do you recommend?
Try this
Object[] completeArray = new Object[0];
completeArray = ArrayUtils.addAll(completeArray, obj1);
completeArray = ArrayUtils.addAll(completeArray, obj2);
If you make both classes implement a common interface you can manipulate arrays/lists of them as if they contains instances of the interface.
public interface Follow {
public String getRequest_id();
public String getState();
}
public class Follower implements Follow {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
public class Following implements Follow {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
public void test() {
List<Follow> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Follow f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Alternatively you could put them in a hierarchy:
public class Entity {
private String request_id;
private String state;
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
}
public class Follower extends Entity {
private String number_sender;
public String getNumber_sender() {
return number_sender;
}
}
public class Following extends Entity {
private String name;
public String getName() {
return name;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Entity f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Or you could make the extra fields into attributes.
enum Attribute {
Follows,
Followed;
}
public static class Entity {
private String request_id;
private String state;
EnumMap<Attribute, String> attributes = new EnumMap<>(Attribute.class);
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
// Factory to make entities.
static Entity make(Attribute attribute, String value) {
Entity e = new Entity();
e.attributes.put(attribute, value);
return e;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(Entity.make(Attribute.Follows, "Fred"));
all.add(Entity.make(Attribute.Followed, "Gill"));
for (Entity f : all) {
String id = f.getRequest_id();
String state = f.getState();
}
}
There are an infinite number of possibilities.
USE concat
var combined= obj1.concat(obj2); // Merges both arrays
Try this.
private Object[] appendObj(Object[] obj, Object newObj) {
ArrayList<Object> temp = new ArrayList<Object>(Arrays.asList(obj));
temp.add(newObj);
return temp.toArray();
}