I have enum:
public enum Enumz{
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three")
private int id;
private String name;
}
How can I find enum value if my String value match with enum string name? For example: if I have String = "two" I need to get ENUMZ.SECOND_VALUE.
public enum Enumz {
FIRST_VALUE(0, "one"),
SECOND_VALUE(1, "two"),
THIRD_VALUE(2, "three");
private int id;
private String name;
Enumz(int id, String name) {
this.id = id;
this.name = name;
}
public static Enumz fromString(String text) {
for (Enumz b : Enumz.values()) {
if (b.name.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
class Sample{
public static void main(String[] args) {
System.out.println(Enumz.fromString("two"));
}
}
You can implement your own method inside enum and call that method every time you want enum using String.
Above code will printing an output as below
OUTPUT
SECOND_VALUE
You can use Java 8 stream alternative to for loop
String serachValue = "two";
Enumz enumz = Arrays.stream(Enumz.values())
.filter(v -> serachValue.equalsIgnoreCase(v.name))
.findFirst().orElse(null);
Good practice is always put it as a static method into the ENUM itself as explained by other #Sagar Gangwal.
Related
I have the following enum Group whick I am unsing to return the right id String depends on the parameter word2 String.
Code 1
public enum Group {
KG1("10460"),
KG2("10461"),
KG3("10462"),
KG4("10463");
private Group (String id){
this.id = id;
}
private final String id;
public String getId(){
return id;
}
public static String getGroupByWord2(String word2){
if(word2.contains("other company")){
return KG3.toString();
}else if(word2.contains("neu company")){
return KG1.toString();
}
return "";
}
#Override
public String toString() {
return getId();
}
}
Now I want to add the information other company, neu company to the enum fields. Therefore I changed the enum to this form below but I am facing probem
that it does not deliver the same result as of the code 1. How can add the Strings other company, neu company to enum fields to deliver the same result as in code 1?
Code 2
public enum Group {
KG1("10460", "neu company"),
KG2("10461", ""),
KG3("10462", "other company"),
KG4("10463", "");
private Group (String id, String word){
this.id = id;
this.word = word;
}
private final String id;
private final String word;
public String getId(){
return id;
}
public String getWord() {
return word;
}
public static String getGroupByWord2(String word2){
for (Group group : Group.values()) {
if (word2.contains( group.getWord())) {
return group.getId();
}
}
return null;
}
#Override
public String toString() {
return getId();
}
}
The code is actually working fine, the difference between the two snippets is equalsIgnoreCase() vs contains() and KG2 value is empty string which will match any non-null String value. Test and formatted code with changed contains() to equals() is below:
public static void main(String[] args) {
System.out.println(Group.getGroupByWord2("neu company")); //10460
System.out.println(Group.getGroupByWord2("other company")); //10462
System.out.println(Group.getGroupByWord2("non existing")); //null
System.out.println(Group.getGroupByWord2(" ")); //null
}
public enum Group {
KG1("10460", "neu company"),
KG2("10461", ""),
KG3("10462", "other company"),
KG4("10463", "");
Group(String id, String word) {
this.id = id;
this.word = word;
}
private final String id;
private final String word;
public String getId() {
return id;
}
public String getWord() {
return word;
}
public static String getGroupByWord2(String word2) {
for (Group group : Group.values()) {
if (word2.equalsIgnoreCase(group.getWord())) {
return group.toString();
}
}
return null;
}
#Override
public String toString() {
return getId();
}
}
In the first version, you check if word2 is either other company or neu company and return appropriate enum's String representation. But in the second one, you are checking word2.contains(group.getWord()) which is going to return true when group.getWord() is an empty string and hence you cannot make word an empty string for the rest of the enums.
If empty strings are not one of the valid cases (valid word2), then just add a condition to check for empty string
if (!group.getWord().isEmpty() && word2.contains(group.getWord()))
One more difference is that at the end (when no match is found) you return null as opposed to an empty string in version 1.
I have a String in this format (including curly brackets):
{id=123, vehicle_name=Tesla Model X, price=80000.00, ... }
What is the appropriate Java object to represent this String, and how can I convert it to that object?
I would like to be able to query the object to retrieve its values easily, eg. obj.get("vehicle_name"). I've tried converting it to JSON using JSONObject however this expects colons as the delimiters between keys and values, rather than the equals sign.
String itself is a java object.
Parsing String and filling up a java object is not clean.
You can create a java pojo Vehicle with attributeS like id,
vehicle_name etc. Assuming your String will always follow a same
pattern.
Parse the String, and fill this Vehicle pojo.
Below is just a simple example, on how to do it :-
public class Test {
public static void main(String[] args){
String text="{id=123, vehicle_name=Tesla Model X, price=80000.00}";
text=text.replaceAll("[{}]", "");
String[] commaDelimitArray=text.split(",");
Vehicle vehicle=new Vehicle();
for(int i=0;i<commaDelimitArray.length;i++){
String[] keyValuePair=commaDelimitArray[i].split("=");
String key=keyValuePair[0].trim();
String value=keyValuePair[1].trim();
if("id".equals(key)){
vehicle.setId(value);
}
else if("vehicle_name".equals(key)){
vehicle.setVehicleName(value);
}
else if("price".equals(key)){
vehicle.setPrice(value);
}
}
System.out.println(vehicle.getId()+" |"+vehicle.getVehicleName());
}
static class Vehicle{
private String id;
private String vehicleName;
private String price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}
This appears to be an assignment in creating Object classes. If so, you want to create something like this:
public class Car {
int id;
String name;
double price;
//include any other necessary variables
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
//include any other variables in constructor header and body
}
public void setID(int newID) {
id = newID;
}
public int getID() {
return id;
}
//add getters and setters for other variables in this same manner
}
Note that you could alternatively create a constructor that takes no parameters and initializes variables to default values, then set the values individually using the setter methods.
In your main class, what you want to do is extract the appropriate substrings from your String to pass to the constructor (or setters). There are various ways of doing this (you can read about some ways here); I would personally recommend using regular expressions and a Matcher.
If I had such a string which needed to be converted to an object I would create a class with a static method which returns a Vehicle object. Then you can do whatever you want with that object. A few getters and setters and you should be good to go.
I have come up with some code which should work as you expect if I have understood your question :)
There is quite a few comments so this should help you understand the code logic.
The Vehicle Class is where all parsing happens in the static method named createVehicle(String keyValueString).
The main class:
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
String vehicleString = "{id=123, vehicle_name=Tesla Model X, price=80000.00}";
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Vehicle vehicle;
// call the static method passing the string for one vehicle
vehicle = Vehicle.createVehicle(vehicleString);
// if the id is -1, then the default constructor fired since
// there was an error when parsing the code.
if(vehicle.getId() == -1 ) {
System.out.println("Check your data buddy.");
} else {
vehicles.add(vehicle);
}
for(Vehicle v : vehicles){
System.out.println("Vehicle id: " + v.getId());
System.out.println("Vehicle name: " + v.getVehicle_name());
System.out.println("Vehicle price: " + v.getPrice());
System.out.println();
}
}
}
The Vehicle Class:
import java.math.BigDecimal;
public class Vehicle {
// declare your attributes mapped to your string
private int id;
private String vehicle_name;
private BigDecimal price;
// Start Constructor
// Default Constructor
public Vehicle() {
this.setId(-1);
this.setVehicle_name("Empty");
this.setPrice(new BigDecimal(0.00));
}
public Vehicle(int id, String vehicle_name, BigDecimal price) {
this.setId(id);
this.setVehicle_name(vehicle_name);
this.setPrice(price);
}
// End Constructor
// Start Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicle_name() {
return vehicle_name;
}
public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
// End Getters and Setters.
// Start Methods and Functions
// Given a string returns a string array split by a "," and with
// "{}" removed.
private static String[] splitString(String keyValueString) {
String[] split;
// Clean string from unwanted values
keyValueString = keyValueString.replaceAll("[{}]", "");
split = keyValueString.split(",");
return split;
}
// Add a vehicle given a formatted string with key value pairs
public static Vehicle createVehicle(String keyValueString) {
int id = 0;
String vehicle_name = "";
BigDecimal price = null;
String[] split;
Vehicle vehicle;
split = splitString(keyValueString);
// Loop through each keyValue array
for(String keyValueJoined : split){
// split the keyValue again using the "="
String[] keyValue = keyValueJoined.split("=");
// remove white space and add to a String variable
String key = keyValue[0].trim();
String value = keyValue[1].trim();
// check which attribute you currently have and add
// to the appropriate variable
switch(key){
case "id":
id = Integer.parseInt(value);
break;
case "vehicle_name":
vehicle_name = value;
break;
case "price":
try {
price = new BigDecimal(Double.parseDouble(value));
} catch (NumberFormatException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Attribute not available");
return null;
}
}
// if any of the values have not been changed then either the
// data is incomplete or inconsistent so return the default constructor.
// Can be removed or changed if you expected incomplete data. It all
// depends how you would like to handle this.
if(id == 0 || vehicle_name.equals("") || price == null){
vehicle = new Vehicle();
} else {
//System.out.println(id);
vehicle = new Vehicle(id, vehicle_name, price);
}
return vehicle;
}
// End Methods and Functions
}
The program, given the string provided, returns the following when accessing the newly created object attributes using the getters:
Vehicle id: 123 Vehicle name: Tesla Model X Vehicle
price: 80000
Hope this helps.
First, thank you for your help!!
What I want to make with an Enumeration class is a Menu of a restaurant. The menu components have its own id which is number, and name.
001("Pasta"),
002("Pizza"),
003("Nuddle"),
004("Steak"),
005("Rice")
Above code my first idea but, I got errors, so I thought only String value can be the components of Enumeration. So, I changed the code like below but it generated error again.
"001"("Pasta"),
"002"("Pizza"),
"003"("Nuddle"),
"004"("Steak"),
"005"("Rice")
The numbers are just IDs of food, so it can have String type. How can I make it?
Enums names cannot start with numbers. If you want to use Enums, I would suggest to use something like this:
public enum Food {
PASTA("Pasta", 1),
PIZZA("Pizza", 2);
/** state variables */
private String name;
private int id;
/** Constructor */
Food(String name, int id) {
this.name=name;
this.id=id;
}
/** Accessors */
public String getName() {
return name;
}
public int getId() {
return id;
}
}
you can use in this way. Or how about add some character like...F001, F002
public class Tester {
static enum Food {
PASTA("001"), PIZZA("002"), NOODLE("003");
private String number;
Food(String number){
this.number = number;
}
public String getNumber(){
return this.number;
}
}
public static void main(String[] args) {
System.out.println( Food.PIZZA.getNumber());
}
}
You can do something like this. First create a static map and put number and string value as a key value pair and write a utility to retrieve a food value based on the given number key value after creating your constructor to populate both fields.
public enum MenuEnum {
ONE(1, "Pasta"), TWO(2, "Pizza"), THREE(3, "Noodle");
private int number;
private String name;
private MenuEnum(int number, String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public String getFoodByNumber(int key) {
return foodMap.get(key) != null ? foodMap.get(key) : null;
}
private static final Map<Integer, String> foodMap = new HashMap<Integer, String>();
static {
for (MenuEnum val : MenuEnum.values()) {
foodMap.put(val.getNumber(), val.getName());
}
}
I have an array list which contains arrays of type String. I create the array list and add arrays to it with the following code:
List<String[]> transaction = new ArrayList<String[]>();
String[] transactionLine = new String[7];
transactionLine[0] = "0";
transactionLine[1] = "1";
//.....
transactionLine[6] = "some value";
transactionLines.add(transactionLine);
Now I want to test if one of the arrays contain a certain value. I tried it like this, but then it checks for an array and not an element of an array:
if(transactionLines.contains("some value")) {
//Do some stuff with it
}
I know this doesn't work, but I don't now how to do it otherwise. I couldn't find any post of this already on Stackoverflow (not with the logical search terms for this problem anyway).
Note: I have chosen this structure of arrays in an arraylist, because I have a fixed number of columns (as suggested in how to create dynamic two dimensional array in java?).
Any help is greatly appreciated!
#assylias suggestion to use the object oriented way is good, but his example does not tell if the list contains a transaction where one property has a certain value. This example does:
public class Test {
public static void main(final String[] args) {
final List<TransactionLine> transaction = new ArrayList<>();
transaction.add(new TransactionLine(1, "some value"));
transaction.add(new TransactionLine(2, "another value"));
transaction.add(new TransactionLine(3, "yet another value"));
System.out.println(containsName(transaction, "some value"));
System.out.println(containsName(transaction, "non-existent value"));
}
// Iterates over all transactions until a transaction is found that has the
// same name as specified in search
private static boolean containsName(final List<TransactionLine> transaction, final String search) {
for (final TransactionLine transactionLine : transaction) {
if (transactionLine.getName().equals(search)) {
return true;
}
}
return false;
}
private static class TransactionLine {
private int id;
private String name;
public TransactionLine(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
}
Here is an example with two classes (Transaction and TransactionLine):
Test:
public class Test {
public static void main(final String[] args) throws Exception {
final Transaction transaction = new Transaction();
transaction.add("some name");
transaction.add("another name");
transaction.add("yet another name");
System.out.println(transaction.containsName("some name"));
System.out.println(transaction.containsName("non-existent name"));
}
}
Transaction:
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private final List<TransactionLine> transactionLines = new ArrayList<>();
public void add(final String name) {
final TransactionLine tl = new TransactionLine(transactionLines.size(), name);
transactionLines.add(tl);
}
public boolean containsName(final String name) {
for (final TransactionLine transactionLine : transactionLines) {
if (transactionLine.getName().equals(name)) {
return true;
}
}
return false;
}
}
TransactionLine:
public class TransactionLine {
private int id;
private String name;
public TransactionLine() {
}
public TransactionLine(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
The object oriented way of solving your problem would be to create a class:
class Transaction {
private final int id;
private final String name;
//etc.
}
Then if you need to test if a given transaction is in the list you could implement equals and hashcode in that class, which would enable you to call:
if(transactionLines.contains(someTransaction)) { ... }
If you just need to find transactions with a specific characteristics, you would need to iterate over the list and check each transaction, for example:
Transaction result = null;
for (Transaction t : transacionLines) {
if(t.getName().equals("some value") {
result = t;
break;
}
}
public static boolean isListOfStringArraysContainsString(List<String[]> arrayList, String s) {
for (String[] arr : arrayList) {
for (String string : arr) {
if ((string != null) && (string.equals(s))) {
return true;
}
}
}
return false;
}
Provided code do exactly what you are asking about, but solution provided by #assylias is proper
I got your point. By using ArrayList you are trying to make an array of another array of strings. But you have made one simple mistake.This is how you tried to retrieved a String inside an array inside an ArrayList:
if(transactionLines.contains("some value")) {
//Do some stuff with it
}
This "some value" is a string present in String array "transactionLine" and not referred by the List "transactionLines" (which is referring to ArrayList object).
Instead this is what you should have done:
List<String[]> transactionLines = new ArrayList<String[]>();
String[] transactionLine = new String[7];
transactionLine[0] = "0";
transactionLine[1] = "1";
transactionLine[2] = "something";
transactionLine[3] = "3";
transactionLine[4] = "4";
transactionLines.add(transactionLine);
String[] mySL=transactionLines.get(0);
System.out.println(mySL[2]);
if (mySL[2].equals("something")) {
//some code
} else {
//some code
}
Hope this helps.
public class MyObject
{
public static enum Type {A, B, C, D;}
public static final int ID_MAIN = 1;
public static final int ID_MAIN_UK = 2;
public static final int ID_MAIN_US = 3;
public static final int ID_SUB = 4;
// lots more constants here
public static final String DESCRIPTION_1 = "Desc Full Name";
public static final String DESCRIPTION_2 = "Desc2 Full Name";
// lots more constants here
private int id;
public MyObject(final int id)
{
this.id = id;
}
//simple getter
public int getID() { return this.id;}
// real responsibility of the class is in the following two methods
public static String getDescription()
{
switch(id)
{
case MyObject.ID_MAIN:
case MyObject.ID_MAIN_UK:
return MyObject.DESCRIPTION_1;
case MyObject.ID_SUB:
return MyObject_Description_2;
default:
// throw IllegalArgException
}
}
public static Type getType(int id)
{
switch(id)
{
case MyObject.ID_MAIN:
case MyObject.ID_SUB:
return Type.A;
case MyObject.ID_MAIN_UK:
case MyObject.ID_MAIN_US:
return Type.B;
default:
return Type.Undefined;
}
}
}
Basically, there is an ID that maps to both a description and a type. This ID is passed in during construction of the class and it should map to a set of constants already contained in the class. If the id is not part of the list of constants, an error is thrown when trying to get the description that maps to the id and an 'Unknown' type is return if the type is queried. The ID maps a description to a set of constants. The same ID maps to a certain Type (defined as an enum).
This code is pretty ugly because there are tons of constants defined at the top, which makes the switch statements pretty bloated. Is there a simple way to refactor this without changing the public interface? It seems trivially simple, but it seems pretty ugly no matter how you slice it. How can I simplify these mappings to make the code more concise?
I was thinking about representing the mappings in a text file and having a manager class that held simple containers in a hashmap. When the manager class is constructed, it would create the objects by reading the text file and map them to an ID. When the manager is queried with the ID, it would just call the corresponding get method, for instance:
class Manager
{
private HashMap<int, MyObject> objectMap;
public Manager() {} //construct the object map
public String getDescription(int id) { return objectMap.get(id).getDescription();}
public Type getType(int id) { return objectMap.get(id).getType();}
}
class DataContainer
{
private String description;
private Type type;
public DataContainer(String desc, Type type) {//set mem vars}
public String getDescription() //simple getter
public Type getType() //simple getter
}
But this solution seems too complicated. Is there a better solution, preferably one that would keep everything in one class?
You can do something like following. This would be much cleaner and manageable.
public enum Type
{
MAIN(1, "Main Description"),
MAIN_UK(2, "Main UK Description"),
//....
//Define all the types
//....
UNKNOWN(-1, "Unknown Type");
private int id;
private String description;
private Type(int id, String description)
{
this.id = id;
this.description = description;
}
public static Type getById(int id)
{
for (Type type : Type.values())
{
if (id == type.getId())
{
return type;
}
}
return Type.UNKNOWN;
}
public final int getId()
{
return id;
}
public final String getDescription()
{
return description;
}
}
public class MyObject
{
private int id;
private Type type;
public MyObject(int id)
{
this.id = id;
this.type = Type.getById(id);
}
public int getId()
{
return id;
}
public Type getType()
{
return type;
}
public String getDescription()
{
return type.getDescription();
}
}
In Java enums can have methods. For example following one accepts ID and description and provides some accessors.
public enum Type {
MAIN(1, "desc1"),
UK(2, "desc2"),
SUB(4, "desc4");
private int id;
private String desc;
Type(int id, String desc) {
this.id = id;
this.desc = desc;
}
public String getDescription() {
return desc;
}
public int getType() {
//return id;
return 1+2 + 3+ id;
}
}
You could use that to improve design.