Return value from ENUM [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a Java ENUM where I store different statuses:
public enum BusinessCustomersStatus {
A("active", "Active"),
O("onboarding", "Onboarding"),
NV("not_verified", "Not Verified"),
V("verified", "Verified"),
S("suspended", "Suspended"),
I("inactive", "Inactive");
#Getter
private String shortName;
#JsonValue
#Getter
private String fullName;
BusinessCustomersStatus(String shortName, String fullName) {
this.shortName = shortName;
this.fullName = fullName;
}
// Use the fromStatus method as #JsonCreator
#JsonCreator
public static BusinessCustomersStatus fromStatus(String statusText) {
for (BusinessCustomersStatus status : values()) {
if (status.getShortName().equalsIgnoreCase(statusText)) {
return status;
}
}
throw new UnsupportedOperationException(String.format("Unknown status: '%s'", statusText));
}
}
Full code: https://github.com/rcbandit111/Search_specification_POC/blob/main/src/main/java/org/merchant/database/service/businesscustomers/BusinessCustomersStatus.java
The code works well when I want to get the list of items into pages for the value fullName because I use #JsonValue annotation.
I have a case where I need to get the shortValue for this code:
return businessCustomersService.findById(id).map( businessCustomers -> businessCustomersMapper.toFullDTO(businessCustomers));
source: https://github.com/rcbandit111/Search_specification_POC/blob/316c97aa5dc34488771ee11fb0dcf6dc1e4303da/src/main/java/org/merchant/service/businesscustomers/BusinessCustomersRestServiceImpl.java#L77
But I get fullValue. Do you know for single row how I can map the shortValue?

Yo can use this :
public enum decizion{
YES("Y"), NO("N"), OTHER;
String key;
decizion(String key) { this.key = key; }
//default constructor, used only for the OTHER case,
//because OTHER doesn't need a key to be associated with.
decizion() { }
static decizion getValue(String x) {
if ("Y".equals(x)) { return YES; }
else if ("N".equals(x)) { return NO; }
else if (x == null) { return OTHER; }
else throw new IllegalArgumentException();
}
}
Then, in the method, you can just do:
public static decizion yourDecizion() {
...
String key = ...
return decizion.getValue(key);
}

Related

How to convert Java enum to Swift enum? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Below is my java enum.
I want to convert it to Swift enum.
Can you please help me to migrate?
package com.lifeplus.Pojo.Enum;
public enum GattServiceEnum {
CURR_TIME_SERVICE("00001805-0000-1000-8000-00805f9b34fb", "current_time"),
DEVICE_INFORMATION_SERVICE("0000180a-0000-1000-8000-00805f9b34fb", "device_information"),
PULSE_OXY_SERVICE("00001822-0000-1000-8000-00805f9b34fb", "pulse_oximeter"),
CUSTOM_SERVICE("4C505732-5F43-5553-544F-4D5F53525600", "Custom Service");
private final String _id;
private final String _desc;
GattServiceEnum(String pId, String pDesc) {
_id = pId;
_desc = pDesc;
}
public String getId() {
return _id;
}
public String getDesc() {
return _desc;
}
}
Plaese help me to convert this to Java.
There is no need to use an enum. You can simply use a struct
public struct GattService {
public let id: String
public let desc: String
// You can optionally provide the get functions, but it is simpler just to access the properties directly
public func getId() -> String {
return id
}
public func getDesc() -> String {
return desc
}
}
try thisŲŒ Hopefully it will be useful for you:
public enum GattServiceEnum {
case myNameCase(id: String, desc: String)
case anotherCase
case onlyIdCase(id: String)
case onlyDescCase(desc: String)
public func getId() -> String? {
switch self {
case .myNameCase(let id, _),
.onlyIdCase(let id):
return id
case .anotherCase, .onlyDescCase:
return nil
}
}
public func getDesc() -> String? {
switch self {
case .myNameCase(_, let desc),
.onlyDescCase(let desc):
return desc
case .anotherCase, .onlyIdCase:
return nil
}
}
}
// create
let myEnumObject = GattServiceEnum.myNameCase(id: "123", desc: "hi")
// get id
print(myEnumObject.getId())
// get desc
print(myEnumObject.getDesc())

What should be the Java object for this JSON String? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
{"userId":"vincent","favTracks":{"favourite":"15","unFavourite":"121"}}
What can be the Java object for the above JSON String?
It really depends on how you want to map it. If you're using Jackson, for example, with the default mapping settings, your classes could look something like:
class MyObject {
private String userId;
private FavTracks favTracks;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public FavTracks getFavTracks() {
return favTracks;
}
public void setFavTracks(FavTracks favTracks) {
this.favTracks = favTracks;
}
}
class FavTracks {
private String favourite;
private String unFavourite;
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
public String getUnFavourite() {
return unFavourite;
}
public void setUnFavourite(String unFavourite) {
this.unFavourite = unFavourite;
}
}
One remark: in your current example, the favourite and unFavourite properties are of a string type. Maybe a numeric type is more suitable?

Compilation error in method call [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
class Persons {
private String name;
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
public class pa {
public static void main(String ar[]) {
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons());
System.out.print(max);
}
}
you do not have default constructor in your Persons class
change
max = a.equal(new Persons());
to
max = a.equal(new Persons("someValue"));
or provide default constructor
You only have 1 constructor in class Person
public Persons(String name) {
this.name = name;
}
But, you create a new instance of Person like this:
max = a.equal(new Persons());
Solutions:
Create a default constructor : public Persons () { }
Use existing constructor : max = a.equal(new Persons(""));
Always add a default constructor when providing a parametrized one.
class Persons {
private String name;
public Persons(){
}
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
You don't have a default constructor for Person,
max = a.equal(new Persons("")); // <-- need a String.
Also, you should name your method equals(), because that's the Object method;
#Override
public boolean equals(Object p) {
if (p instanceof Persons) {
return this.name.equals(((Persons) p).name);
}
return false;
}
also you do not have constructor like this :
public Persons() //no parameter
{
this.name = name;
}
so you can't create a new instance of Persons (wow! too many person.) using the above constructor.
Issue is here
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons()); // Persons class don't have no-argument construtor
You have to change this to
max = a.equal(new Persons("yourValue"));
Or you can add no argument constructor to Persons class.
public Persons(){
}

How to manipulate value from a return string in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a variable that contains a return value.
Value:
Team ID:
111111
Founded:
Feb 13, 2014 By USER
Dispute Percentage:" 0%
Reputation: -
What I am looking to keep is stickly (11111) and save it back to the value teamID. How can I manipulate the return string to only store that value and delete the rest.
If I understand what you want, you can do something like this
String value = "Team ID:\n" + "19288568\n"
+ "Founded:\n" + "Feb 13, 2014 By MLGQA\n"
+ "\n" + "Dispute Percentage: 0%\n"
+ "Reputation: -\n";
System.out.println(value.split("\n")[1]);
Outputs
19288568
Since your returned String seems somewhat complex to me, I would suggest returning a custom object (a bean) containing the information you want, each with its own field.
By doing that, you will have a quick access to any of the fields you want, by simply calling the appropriate getter method on the returned object.
For example:
public class MyContainer {
private int teamID;
private String foundationDate;
private String foundator;
private int disputePercentage;
private int reputation;
public MyContainer() {
// Constructor code.
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public String getFoundationDate() {
return foundationDate;
}
public void setFoundationDate(String foundationDate) {
this.foundationDate = foundationDate;
}
public String getFoundator() {
return foundator;
}
public void setFoundator(String foundator) {
this.foundator = foundator;
}
public int getDisputePercentage() {
return disputePercentage;
}
public void setDisputePercentage(int disputePercentage) {
this.disputePercentage = disputePercentage;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
}
And your original returning method would look to something like this:
public MyContainer returningMethod(Object args) {
// Your code.
MyContainer bean = new MyContainer();
// Fill the container.
return bean;
}
I do not know the exact types of data you use, so feel free to adjust this example for your needs!

Lookup within the enum constants by constant specific data [duplicate]

This question already has answers here:
How to retrieve Enum name using the id?
(11 answers)
Closed 9 years ago.
I need to do look up in an enum by an int . The enum is as folows :
public enum ErrorCode{
MissingReturn(1,"Some long String here"),
InvalidArgument(2,"Another long String here");
private final int shortCode ;
private final String detailMessage;
ErrorCode(shortCode ,detailMessage){
this.shortCode = shortCode ;
this.detailMessage= detailMessage;
}
public String getDetailedMessage(){
return this.detailMessage;
}
public int getShortCode(){
return this.shortCode ;
}
}
Now Is need to have a lookup method that would take an int code and should return me the String message pertaining to that code that is stored in the Enum.Passing a "1" should return me the String "Some long String here". What is the best way to implement this functionality?
public static String lookUpMessageFromCode(int code){
}
P.S: Is the class EnumMap useful for this kind of use case? If yes,please let me know why?
Depending on the int values that you associated with your enum, I would add a static array of ErrorCodes, or a static Map<Integer,ErrorCode> to your enum class, and use it to do a lookup in the message from code method. In your case, an array is more appropriate, because you have values 1 and 2 which are small. I would also change the signature to return ErrorCode.
private static final ErrorCode[] allErrorCodes = new ErrorCode[] {
null, MissingReturn, InvalidArgument
};
public static ErrorCode lookUpByCode(int code) {
// Add range checking to see if the code is valid
return allErrorCodes[code];
}
The callers who need the message would obtain it like this:
String message = ErrorCode.lookUpByCode(myErrorCode).getDetailedMessage();
I would simply iterate through your Enum values and check the code. This solution lets you utilize the existing Enum with out creating another object to manage.
public enum ErrorCode {
MissingReturn(1, "Some long String here"),
InvalidArgument(2, "Another long String here");
private final int shortCode;
private final String detailMessage;
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
public String getDetailedMessage() {
return this.detailMessage;
}
public int getShortCode() {
return this.shortCode;
}
public static String lookUpMessageFromCode(int code) {
String message = null;
for (ErrorCode errorCode : ErrorCode.values()) {
if (errorCode.getShortCode() == code) {
message = errorCode.getDetailedMessage();
break;
}
}
return message;
}
public static void main(String[] args) {
System.out.println(ErrorCode.lookUpMessageFromCode(1));
System.out.println(ErrorCode.lookUpMessageFromCode(2));
}
}
One thing to note
The Enum constructor is missing the type information regarding its parameters.
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
Here is another option:
public static String lookUpMessageFromCode(int code){
for(ErrorCode ec:ErrorCode.values()){
if(ec.shortCode==code)
return ec.detailMessage;
}
return null;
}

Categories

Resources