how can I get enum value by name string - java

I want to get the enum value by name string,
this the enum code:
package practice;
enum Mobile {
Samsung(400),
Nokia(250),
Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
I can get the class name and the name string
Class enumClass = Class.forName("practice.Mobile");
String name = "Samsung";
how can I get the Samsung value 400 only use enumClass and name?
thanks a lot

You can use something like:
final Mobile mobile = Mobile.valueOf("Samsung");
final int price = mobile.showPrice();
(you do have to change the scope of the method showPrice() to public).

as you may know, there is a valueOf method in every enum, which returns the constant just by resolving the name(read about exceptions when the string is invalid.)
now, since your enum has another fields associated to the constants you need to search its value by matching those fields too...
this is a possible solution using
java 8
public enum ProgramOfStudy {
ComputerScience("CS"),
AutomotiveComputerScience("ACS"),
BusinessInformatics("BI");
public final String shortCut;
ProgramOfStudy(String shortCut) {
this.shortCut = shortCut;
}
public static ProgramOfStudy getByShortCut(String shortCut) {
return Arrays.stream(ProgramOfStudy.values()).filter(v -> v.shortCut.equals(shortCut)).findAny().orElse(null);
}
}
so you can "resolve" the enum by searching its "shortcut"
like
System.out.println(ProgramOfStudy.getByShortCut("CS"));

Related

What is the best practice to handle related constant strings in Java? [duplicate]

This question already has answers here:
What is the best way to implement constants in Java? [closed]
(28 answers)
Closed 7 months ago.
Let us assume that I have to handle several constant strings that are closely related, for example types of messages ("ID1", "ID2", "ID3"). Currently I use a final class that only has public static final definitions:
public final class MessageType {
public static final String ID1 = "ID1";
public static final String ID2 = "ID2";
public static final String ID3 = "ID3";
}
In the various classes I access the strings as MessageType.ID<X>.
Is this the best way to handle this scenario or the best practice is different?
Thanks.
This approach has one big drawback: There's no decent way to transform a String such as "ID1" back to MessageType.ID1.
The common approach here is to use an enum:
public enum MessageType {
ID1,
ID2,
ID3
}
Their String representation is MessageType.ID1.name(). You can transform the name back to a constant by iterating over MessageType.values().
This has the limitation that the constants need to be valid regarding the java syntax. Enums are basically a list of instances of that enum class. Writing down the constant names is essentially a call to a constructor. That means you can assign values to each instance:
public enum MessageType {
ID1("ID 1"), //calls the constructor
ID2("something else with spaces");
private final String text; //field
MessageType(String t) { //the constructor
this.text = t;
}
//and the lookup:
static MessageType getByText(String text) {
for(MessageType t:values()) {
if(t.text.equals(text)) {
return t;
}
}
return null;
}
public String getText() {
return text;
}
}
You can now access these longer Strings using MessageType.ID2.text. Calling MessageType.getByText("ID 1") will return MessageType.ID1.

Multiple comparators in a class

I am hard stuck on a problem I cannot find a good answer to. I've found
this one about custom comparators, but it is incomplete:
class YourClass {
static Comparator<YourClass> getAttribute1Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 1
};
}
static Comparator<YourClass> getAttribute2Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 2
};
}
}
That should work, but I don't know how the comparison part works. Here is my class:
package ZVCVolkel_Logic;
import java.util.Comparator;
public class Vliegtuig implements Comparator<Vliegtuig>{
private String naam;
private String type;
private String status;
private Hangaar hangaar;
public Vliegtuig(String naam, String type, String status, Hangaar hangaar){
this.naam = naam;
this.type = type;
this.status = status;
this.hangaar = hangaar;
}
}
Now I need a comparator for status and for Hangaar.getName(). Can someone help?
It is not the one, he has only 1 comparator. I can get that working too but not with 2 different ones in 1 class.
The comparator interface has a method compare return an int value to determine the relation ship between two objects.
It will return:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
static Comparator<Vliegtuig> hangaarNameComparator() {
return new Comparator<Vliegtuig>(){
public int compare(Vliegtuig one, Vliegtuig two) {
return one.getHangaar().getName().compareTo(two.getHangaar().getName());
}
}
}
Here you probably want to take care of NullPointerException if getHangaar() or hangaar.getName() return null.
In java 8 you could do this:
Comparator<Vliegtuig> hangaarNameComparator = Comparator.comparing(Vliegtuig::getHagaar,
Comparator.comparing(Hagaar::getName));
In the comparator implementation you need to compare 2 objects. You can refer to most of JDK classes for example, for instance java.lang.Integer.
In your case solution will be to use embedded compactors from objects like this:
Comparator<Vliegtuig> nameComparator = new Comparator<>() {
#Override
public int compare(Vliegtuig o1, Vliegtuig o2) {
return o1.getName().compareTo(o2.getName());
}
}
And you don't need to extend Comparator by the Vliegtuig.

Java enum error - return type reqiued

I created simple enum class in java.
public enum XmlElementsInput {
element_sentenceInput("a");
element_sentence("b");
private final String elementName;
private XmlElementsInput(String name) {
this.elementName = name;
}
public String getElementName() {
return elementName;
}
}
But Netbeans say me: invalid method declaration; return type required, ilegal start of type on line element_sentence("b");. I dont know why? Can you tell me why?
The enum types must separated by comma:
element_sentenceInput("a"),
element_sentence("b");
Use commas to separate enum values, as follows:
public enum XmlElementsInput {
element_sentenceInput("a"),
element_sentence("b");
// Remaining part
}

Tuple Enum in Java

I'm very new in Java and were wondering and didn't find anything about it.
Can you create enum tuple ?
public enum Status {OPEN : "1", CLOSED: "2", DELETED: "3"}
I will need to access both "OPEN" or "1"
You could always create a custom constructor for your enum..
public enum Status {
OPEN("1"),
CLOSED("2"),
DELETED("3");
private String code;
public Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
Then you can access with Status.OPEN.getCode(). This functions as an effective mapping between an enum type and a code value.
You can do something like this:-
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
};
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.
private int getValue() { return value; }
and get values like this:-
PENNY.getValue(); //returns int 1
Refrence:
Solution by #christopher cover only first part. Creating ENUM.
You will need one more method that match code with enum value:
public static Status byCode(String code){
for(Status s : Status.values()) {
if (s.code.equals(code)) {
return s;
}
}
throw new IllegalArgumentException("Code does not match");
}
now you can get enum value by name and by code.

Compilation error with ENUM class

sorry for asking such basic question. I am trying some hands on ENUM. below is my code. I am getting some compilation error . Any idea where is the problem. I want SAMPLEMAIL,BULKUSERS,ALLUSERS should be of integer type.
public enum EmailSendingOption {
SAMPLEMAIL, BULKUSERS, ALLUSERS;
private int emailSendingOptionType;
private EmailSendingOption(String optionType) {
int value = Integer.parseInt(optionType.trim());
emailSendingOptionType = value;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
thanks.
You have defined a constructor but you haven't supplied arguments for each of your Enums.
Looks like your constructor should take an integer too. Saves having to parse a String each time. It's also safer.
e.g.
SAMPLEMAIL(10), etc.
With your constructor looking like:
private int emailSendingOptionType;
private EmailSendingOption(int optionType) {
this.emailSendingOptionType = optionType;
}
You need to make it like this:
public enum EmailSendingOption {
SAMPLEMAIL("1"), BULKUSERS("2"), ALLUSERS("3");
private int emailSendingOptionType;
private EmailSendingOption(String optionType) {
int value = Integer.parseInt(optionType.trim());
emailSendingOptionType = value;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
enum are not integers in Java, they are objects. There is no sane reason you would pass an integer as a String to a constructor so it can be parsed into an integer. If you want an integer use an integer.
public enum EmailSendingOption {
SAMPLEMAIL(1), BULKUSERS(2), ALLUSERS(101);
private final int emailSendingOptionType;
private EmailSendingOption(int emailSendingOptionType) {
this.emailSendingOptionType = emailSendingOptionType;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
Since you are providing a custom constructor to your Enum
EmailSendingOption(String optionType)
You need to add those parameter for each Enum constant.
Change it to:
public enum EmailSendingOption
{
SAMPLEMAIL("String"), BULKUSERS("String"), ALLUSERS("String");
...
}
You defined a constructor as needed a String as argument. SAMPLEMAIL this are a static object
of EmailSendingOption.

Categories