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
Related
I want to have a list with almost all the values from an enum. I tried to do that with the help of stream but I don't know why it is not working.
For example I am trying to do like this:
SortingType.stream() //
.filter(d -> !d.getName().equals(SortingType.UNKNOWN.getName()))
.forEach(u -> {
sortingList.add(createSortingBE(locale, u, u.name().equalsIgnoreCase(sortingType.name())));
});
.stream() appears with red and I receive this message : " Cannot resolve method 'stream' in 'SortingType' "
Sorting Type
public enum SortingType {
DISTANCE("DISTANCE", 101, "Sorting POIs by distance"),
PRICE("PRICE", 104, "Sorting POIS by price"),
UNKNOWN("UNKNOWN", 000, "Unknown sorting option");
private String name;
private Integer identifier;
private String description;
SortingType(final String name, final Integer identifier, final String description) {
this.name = name;
this.identifier = identifier;
this.description = description;
}
public static SortingType getByName(final String name) {
return Stream.of(values()).filter(u -> u.name.equalsIgnoreCase(name)).findFirst().orElse(SortingType.UNKNOWN);
}
public static SortingType getByIdentifier(final Integer identifier) {
return Stream.of(values()).filter(u -> u.identifier.equals(identifier)).findFirst().orElse(SortingType.UNKNOWN);
}
public String getDescription() {
return description;
}
public Integer getIdentifier() {
return identifier;
}
public String getName() {
return name;
}
You should simply add the stream() method like this.
public enum SortingType {
// .....
public static Stream<SortingType> stream() {
return Stream.of(values());
}
}
I was asked to make a a column called Type a varchar2(1)which has values partial or all
That what i made in Model.Java
#Column(name="TYPE")
#Enumerated(EnumType.STRING)
public TypeEnum getType() {
return type;
}
public void setType(TypeEnum type) {
this.type = type;
}
And this is my TypeEnum.java
public enum TypeEnum {
ALL(0, "all"),
PARTIAL(1, "partial");
private int code;
private String value;
private TypeEnum(int code, String value) {
this.code = code;
this.value = value;
}
public String getValue() {
return value;
}
public int getCode() {
return code;
}
public static TypeEnum getTypeEnum(String value){
TypeEnum[] types = values();
for(int i=0; i<types.length; i++){
TypeEnum type = types[i];
if(value.equals(type.getValue()))
return type;
}
return null;
}
}
So how to store the TypeEnum in DB to achieve the varchar2(1)
You could use a Converter to map your enums to varchar(1) yourself. Something like:
#Column("TYPE") #Convert(TypeEnumToString.class) TypeEnum type;
with the converter class implemented something like:
public class TypeEnumToString implements AttributeConverter<TypeEnum, String> {
#Override
public TypeEnum convertToEntityAttribute(String value) {
// return conversion;
}
#Override
public String convertToDatabaseColumn(TypeEnum value) {
// return conversion;
}
}
You can achieve this by implementing AttributeConverter<TypeEnum, String>
#Converter
public class TypeEnumConverter implements AttributeConverter<TypeEnum, String> {
#Override
public String convertToDatabaseColumn(TypeEnum attribute) {
return String.valueOf(attribute.getCode());
}
#Override
public TypeEnum convertToEntityAttribute(String dbData) {
return getTypeEnumFromCode(parseInt(dbData));
}
}
getTypeEnumFromCode can be implemented similar to your getTypeEnum method.
Then, define it like
#Column("TYPE")
#Convert(TypeEnumToString.class)
TypeEnum type;
p.s.I just used code from your enum but it can be any other logic too.
I have a POJO class A with the below structure
class A{
private String var1;
private int var2;
private String var3;
}
I have two ArrayList<A> List1 and List2 with different size. I want to remove all elements in List1 which are already present in List2 and this equality needs to be checked with respect to the value stored in var2.
I have already checked making the List a Hashset and using removeAll(). But this wont give the desired output since for the same var2, var1 values differ.
Please help me solve this problem.
Edit 1 - Requested by Murat
public class HistoryDto implements Serializable,Comparable<HistoryDto> {
private Integer id;
private String sId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSId() {
return sId;
}
public void setSId(String sId) {
this.sId = sId;
}
public String getTrackName() {
return trackName;
}
public void setTrackName(String trackName) {
this.trackName = trackName;
}
public String getTrackDescription() {
return trackDescription;
}
public void setTrackDescription(String trackDescription) {
this.trackDescription = trackDescription;
}
public Integer getUsedNo() {
return usedNo;
}
public void setUsedNo(Integer usedNo) {
this.usedNo = usedNo;
}
public String getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getPartyId() {
return partyId;
}
public void setPartyId(Integer partyId) {
this.partyId = partyId;
}
private String trackName;
private String trackDescription;
private Integer usedNo;
private String extraInfo;
private String imageUrl;
private Integer partyId;
public int compareTo(HistoryDto other) {
return this.sId.compareTo(other.sId);
}
}
Removing Items
ListA.removeAll(new HashSet(listB));
You need 2 loops nested.
pseudocode:
for each in A do
for each in B do
if (current item of A equals to current item of B)
say yes!
done
done
You just need to translate it to Java.
You may do it using the Stream API:
Set<Integer> var2 = list2.stream()
.map(a -> a.var2)
.collect(Collectors.toSet());
list1.stream()
.filter(a -> !var2.contains(a.var2))
.collect(Collectors.toList());
i have a Java Enum like below
public enum TestEnum{
{
A("a","b","c"),
B("a1","b1","c1"),
C("a2","b2","c2");
TestEnum(String a,String b,String c){
}
private String a;
private String b;
private String c;
}
I want to externalize this config to an XML file but XSDs donot seem to support attributes on Enum Element type. Is there a way to work this around or an alternate to it.
You could do something like this (even though for enum, this looks too verbose)
#XmlJavaTypeAdapter(CountXmlAdapter.class)
public enum Count {
ONE(1, "one"),
TWO(2, "two"),
THREE(3, "three");
private final int index;
private final String name;
private Count(int index, String name) {
this.index = index;
this.name = name;
}
#XmlAccessorType(XmlAccessType.FIELD)
public static class CountWrapper {
private int index;
private String name;
public CountWrapper() {
}
public CountWrapper(int index, String name) {
this.index = index;
this.name = name;
}
}
public static class CountXmlAdapter extends XmlAdapter<CountWrapper, Count> {
#Override
public Count unmarshal(CountWrapper v) throws Exception {
return v != null ? Count.valueOf(v.name.toUpperCase()) : null;
}
#Override
public CountWrapper marshal(Count v) throws Exception {
return v != null ? new CountWrapper(v.index, v.name) : null;
}
}
}
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");