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;
}
}
Related
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.
I would like to store and retrieve special characters (/, * etc) into/from DB table. This is my attempt:
public enum SpecialCharacters {
Hack("H/K"), Gk("G*M");
private String value;
private SpecialCharacters(String value) {
this.value = value;
}
public String toString() {
return this.value; // This will return , # or +
}
}
#Column(name = "Special_Char")
#Enumerated(EnumType.STRING)
private SpecialCharacters specialCharacters;
...
But in DB table it stores only enum field Names like Hack and Gk, not H/K and G*M
With the #Enumerated Annotation you are only able to store the name or ordinal of your enum. With JPA 2.1 you can use the #Converter Annotation.
See Chapter 11.1.10 of the specification.
Example:
Enum:
public enum SpecialCharacter {
Hack("H/K"),
Gk("G*M");
private String value;
private SpecialCharacter(String value) {
this.value = value;
}
public String toString() {
return this.value; // This will return , # or +
}
public static SpecialCharacter valueOfKey(String key) {
for (SpecialCharacter specialCharacter : values()) {
if (specialCharacter.toString().equals(key)) {
return specialCharacter;
}
}
throw new IllegalArgumentException("Illegal key");
}
}
ConverterClass:
#Converter(autoApply = true)
public class SpecialCharacterConverter implements AttributeConverter<SpecialCharacter, String> {
/**
* Converts a {#link SpecialCharacter} to the correspondig String that is used in the database
*/
#Override
public String convertToDatabaseColumn(SpecialCharacter specialCharacter) {
return specialCharacter.toString();
}
/**
* Converts a String from the database to the corresponding {#link SpecialCharacter}.
*/
#Override
public SpecialCharacter convertToEntityAttribute(String dbValue) {
return SpecialCharacter.valueOfKey(dbValue);
}
}
Entity-Object:
#Entity
public class SomeEntity {
#Column(name = "Special_Char")
private SpecialCharacter specialCharacter;
public SpecialCharacter getSpecialCharacter() {
return this.specialCharacter;
}
public void setSpecialCharacter(SpecialCharacter specialCharacter) {
this.specialCharacter = specialCharacter;
}
}
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();
}
In my page class:
public SelectModel getCountryListEnum() {
return new EnumSelectModel(CountryListEnum.class, resources.getMessages());
}
public CountryListEnumEncoder getCountryListEnumEncoder(){
return new CountryListEnumEncoder();
}
In my template (select.selectcountries extends Tapestry Select Component btw):
<t:select.selectcountries id="country" t:id="country" model="CountryListEnum" value="user.address.countrycode" encoder="CountryListEnumEncoder"/>
my enum:
public enum CountryListEnum {
AFGHANISTAN("Afghanistan", "AF"),
ALBANIA("Albania", "AL"),
ALGERIA("Algeria", "DZ"),
(...ETC);
private String country;
private String code;
private CountryListEnum( String country, String code) {
this.country = country;
this.code = code;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getId() {
return getCode();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private CountryListEnum() {
}
public static int getSize() {
return values().length;
}
public static String getNameFromCode(String code) {
for (CountryListEnum countryEnum : values()) {
if (code.trim().equals(countryEnum.getCode())) {
return countryEnum.getCountry();
}
}
throw new IllegalArgumentException("Country Code: "+ code + " does not exist");
}
}
My ValueEncoder:
public class CountryListEnumEncoder implements ValueEncoder<CountryListEnum>, ValueEncoderFactory<CountryListEnum> {
#Override
public String toClient(CountryListEnum value) {
return value.getId();
}
#Override
public CountryListEnum toValue(String clientValue) {
Validate.notEmpty(clientValue);
for (CountryListEnum countryEnum : CountryListEnum.values()) {
if (clientValue.trim().equals(countryEnum.getCode())) {
return countryEnum;
}
}
throw new IllegalArgumentException("Country Code: " + clientValue + " does not exist");
}
#Override
public ValueEncoder<CountryListEnum> create(Class<CountryListEnum> type) {
return this; //To change body of implemented methods use File | Settings | File Templates.
}
}
Finaly, I am getting the following error:
java.lang.String cannot be cast to
com.starpoint.instihire.api.domain.reference.CountryListEnum
I tried committing a type coercer (as suggested here) but that didn't work either. I also tried omitting the model param from the select and changing the id of the select.selectcountries component to a countryListEnum (as suggested here). Scratching my head on this one...
Looks like user.address.countrycode is a String and not a CountryListEnum
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");