I have an Enum
public enum status{
YES,
NO
}
the input from json string is "Yes" or "No", is there any method in ObjectMapper to match status.YES with "Yes", and status.NO with "No".
I don't want to change enum, because int my previous system, people use the enum all the time, I don't want cause problem for others
You can always redefine it like:
public enum Status {
YES("Yes"),
NO("No");
private final String status;
private Status(final String status) {
this.status = status;
}
public String value() {
return this.status;
}
}
And then use something like this: Status.YES.value();
You can use toString() method available in all Java enums:
http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
and on returned String call compareToIgnoreCase method to compare it with input:
http://www.tutorialspoint.com/java/java_string_comparetoignorecase.htm
Or you can call toUpperCase on input String and then comapre them:
http://www.tutorialspoint.com/java/java_string_touppercase.htm
Finally, you can use toString mentioned earlier and put all letters except the first to lower case:
String YesString = enumWithYESValue.toString().substring(0, 1) + enumWithYESValue.toString().substring(1).toLowerCase();
Based on: How to capitalize the first letter of a String in Java?
Related
Is there any option in java to Create an enum with true and false like below,
public enum options {
true,
false,
both
}
Now getting unexpected token error as I am using true and false. thank you
Regards
haru
No. From JLS 8.9.1, an enum constant is defined in the syntax to be
EnumConstant:
{EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody]
So it's an Identifier. And from JLS 3.8, and Identifier is defined to be
Identifier:
IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral
Hence, an identifier is any valid string of identifier characters (basically letters and numbers, but with Unicode support thrown in) that is not a keyword (like if) or the words true, false, or null.
Realistically, you should be capitalizing your enum names anyway, so it would look more like
public enum Options {
TRUE, FALSE, BOTH
}
which poses no issues as TRUE and FALSE aren't Boolean literals in Java.
The values of your enum should be formatted like constants; all-caps with underscores between words (if they are more than one word, which in your case, they are not). If you need to be able to convert them to/from strings that do not match the name and case of the enum constants, I would suggest adding a parameter with the string and methods to convert in each direction:
public enum Options {
TRUE("true"),
FALSE("false"),
BOTH("both");
private final String description;
private Options(final String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public static Options parse(String description) {
for (Options option : Options.values()) {
if (option.getDescription().equals(description)) {
return option;
}
}
throw new IllegalArgumentException("no such option: " + description);
}
}
If you call Options.parse("true") it will return Options.TRUE and if you call Options.TRUE.getDescription() it will return "true". If you call Options.parse("none") it will throw an IllegalArgumentException.
I have an enum with enum values. I want to print the list of the enum values only.
Not just the enum. I have read about Value Of but see thats not the correct way to go at it.
This is what I want printed:
People Out
People In
Here is my enum with values in it. I added a constructor.
public enum People {
OUT("People out"),
IN("People in");
private final String name;
People(String name) {
this.name = name;
}
}
The method to retrieve the enums is:
public String retrieveEnumValues() {
return Stream.of(People.values()).
map(People::name).collect(Collectors.joining("\n"));
}
What am I doing wrong here?
People::name refers to standard enum's method name(), you should provide getter for your name field and using it People::getName.
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is of length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"
Why can't I use this code:
public String withoutString(String base, String remove)
{
base.replace(remove, "");
return base;
}
base.replace doesn't change the original String instance, since String is an immutable class. Therefore, you must return the output of replace, which is a new String.
public String withoutString(String base, String remove)
{
return base.replace(remove,"");
}
String#replace() returns a new string, doesn't change the one it is invoked on, since strings are immutable. Use this in your code:
base = base.replace(remove, "")
Update your code:
public String withoutString(String base, String remove) {
//base.replace(remove,"");//<-- base is not updated, instead a new string is builded
return base.replace(remove,"");
}
Try following code
public String withoutString(String base, String remove) {
return base.replace(remove,"");
}
For Input :
base=Hello World
remove=llo
Output :
He World
For more on such string operations visit this link.
Apache Commons library has already implemented this method,you don't need to write again.
Code :
return StringUtils.remove(base, remove);
I have a column in database with 5 possible values. I want to map this column as an enum field. The problem is some of these values contain a dash. I tried something like this:
public enum Status {
S1("S1"), S2("S2"), S3("S-3"), S4("S-4"), S5("S5");
private final String text;
Status(String text) {
this.text = text;
}
#Override
public String toString() {
return this.text;
}
But it doesn't work. If the row in database contains value with a dash, I get an error:
Unknown name value [S-3] for enum class [test.package.Status]
Is there any way to map values containing dash to an enum?
The toString() do not work as the evaluation of enum is based on public final String name(). And as this is final you can not override it.
You will have to use another type. In this answer you will get the required info.
have u tried this one in your model
#Enumerated(EnumType.STRING)
Status status
I should take from a variable enum its value and transform it to string.how can i do?
here it is the type enum:
public enum State{
b,c,p;
};
now i have to insert into an object String one value.
You might use enum.name orenum.toString to get the name of the enum constant, or enum.ordinal to get the ordinal position.
you can use name() or toString(), so :
State aState = State.c;
String strState = aState.name();
See here the official java reference for more information...
State.b.toString() will return "b". The same goes for the other ones.
Usually,
State state = ...;
String string = state.toString();
should work, but it is not recommended since someone might override toString for some other purpose.
Instead the method you are looking for is
String string = state.name();
As an aside, your enumerated stated should always be all in capitals, and they should have descriptive names. It's not a language rule, but a convention. For example enum State { ON, OFF, PAUSED; }.
I tend to do something more complicated, but I find that it's more flexible:
public enum MyEnumeration {
SOME_NAME("Some Name"),
OTHER_THING("Other Thing"),
...
MORE_VALUES("More Values"),
private final String displayName;
private MyEnumeration(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This way, I use standard capitalization for my enums in code, but can have a more presentable name for them.
This trick can also be used to replace ordinal, by initializing a number, and then you don't need to worry about rearranging your enums.
Method #1: Using the built-in toString() and name() methods
If you want to print a String that is the same as the value of the State, then you can use the toString() method, or the name() method.
System.out.println(State.b); // Prints "b"
System.out.println(State.c); // Prints "c"
System.out.println(State.p); // Prints "p"
Method #2: Using a constructor to create a custom mapping
If you want to have a custom String associated with each of those states, you can use a constructor to associate a particular value with each enum value:
public enum State{
b("State B"), c("State C"), p("State P");
private String longName;
private State(String longName) {
this.longName = longName;
}
#Override
public String toString() {
return this.longName;
}
};
Of course, if you don't want to break the default toString() usage, you can create a different method called getFullName(), for example, to return the custom value.