I have a LinkedHashMap with a class as the Key as such:
private final Map<Files, String> list = new LinkedHashMap<Files,String>();
Files is a class consisting of 3 variables:
class Files {
public String file;
public String duration;
public String status;
}
Now I need to access the variables in Files using a index. I know that LinkedHashMap does not allow retrieving values using Index, so I tried this:
List<Entry<Files,String>> randAccess = new ArrayList<Entry<Files,String>>(list.entrySet());
Using randAccess.get(index) I can retrieve the Key itself, but not the specific variables inside the class. So the output is somethinglike Files#6aa91761=String.
I want to be able to get the variable, something like: list.Files.status.Get(index) would return return the value of "status" at the right Index.
You can get the Files variables from the Map.Entry using .getKey(). From there you can get the status field directly.
randAccess.get(index).getKey().status
Related
This question already has answers here:
Java: Getter and setter faster than direct access?
(3 answers)
Closed last year.
I have the below class with around 200 variables.
public class BaseDataDTO {
private CSVRecord rawData;
private List<InquiriesDataDTO> inquiriesData;
private ListTradesDataDTO> tradesData;
private List<CollectionsDataDTO> collectionsData;
private Long applicantId;
//cvv attributes
public String adg001;
private String adg002;
private String adg003;
private String adg004;
private String apg05;
-
-
private String apg199;
}
From a different class, I would like to access the instance variables through the variable names, is it possible to do? I need to do this since I need compare some another response with the instance variable of that class through a Map key. How can I achieve some thing to the effect of the text in bold below?
I do not want to use getter methods here since it is in a for loop for 200 times.
BaseDataDTO baseData = CSVParser.parseBaseData(fileName);
Map<String, String> attributes = fileLoader.withName("attributes.json").jsonToObject(Map.class);
for (String key : attributes.keySet()) {
String responseValue = response.getModelScores().get(0).getScoringInput().get("function_input").get(key).asText();
String expValue = baseData.get(key));
AssertEquals(responseValue, expValue);
}
Create a BaseDataDTO from your Map and check for equality via equals.
Never ever access object fields by their name string, unless you are writing low level libraries like parsers.
Accessing fields by name is done via Reflection:
String expValue = (String) BaseDataDTO.class.getDeclaredField(key).get(baseData)
Note that stuff like this is at least an order of magnitude slower than using a getter.
I have a tag like this
public class AcsTag {
public static String getStyles(String paramter) {
return hashMap<String, String>()
}
}
}
I can access this tag in template (scala.html) like this
#import com.twago.fms.shared.ui.AcsTag
#AcsTag.getStyles(paramter)
getStyles method return a HasMap, I want to store that hashMap in a variable and then later get value from this hash map by key. I do want to iterate over map . I specifically want to access values by key.
following code i tried but always give error
"map not defined"
map =#{AcsTag.getStyles(paratmeter))}
#{map.get("themeColor")}
error "map not defined"
To declare a variable, you have to set at the top of your template:
#yourValue = #{yourExpression}
So, to declare a map value, you should do:
#map = #{AcsTag.getStyles(parameter)}
Then you'll be able to use yout map value anywhere in your template. Eg:
<div class="#map.get("themeColor")">...</div>
I'm a java beginner and have a question concerning how to best structure a cooking program.
I have a class called Ingredient, this class currently looks like this:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class.
I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?
Happy for any suggestions, thanks in advance :)
Please do not initialize all these objects in the Ingredient class itself. That would be a bad practice for oops.
Just think your class is a template from which you create copies(objects) with different values for attributes. In real world if your class represent model for a toy plane which you would use to create multiple toy planes but each bearing different name and color then think how such a system would be designed. You will have a model(class). Then a system(another class) for getting required color and name from different selection of colors and names present(like in database,files,property file ) etc.
Regarding your situation .
If predetermined values store the values in a text file,properties file,database,constants in class etc depending on the sensitivity of the data.
Create Ingredient class with constructors
Create a class which will have methods to initialize Ingredient class using predetermined values,update the values if required,save the values to text file -database etc and in your case return as map .
Also check the links below
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Sounds to me like you are looking for a static Map.
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor, String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
static Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
static {
// Build my main set.
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)"));
}
}
I have one Java constant file which contains around 1000 records and all are String type only
e.g.
public static String PF_EMPLOYER = "PF-Employer";
public static String ESI_EMPLOYER = "ESI-Employer";
public static String TOTAL_CTC = "Total CTC";
public static String INCENTIVE = "Incentive";
public static String PF_EMPLOYEE = "PF-Employee";
public static String ESI_EMPLOYEE = "ESI-Employee";
==and so on could be more than 1000=======
I just want all this String values in static ArrayList or HashMap where Integer in HashMap will be 0,1,2,3....1000.
I am stuck to find out any Effective way to complete this task, Even if Spring is providing any solution I am also ready to go with it.
Its not possible for me to Move Constant file content in any Properties file.
Note that I am using JDK 7 not possible to go for JDK 8.
If I correctly understand your requirement, the only natural way of doing what you want should be using reflection. If you class name was ConstClass it could be something like :
HashMap<String, String> map = new HashMap<>();
for (Field field: ConstClass.class.getFields()) {
if (String.class.isAssignableFrom(field.getType())) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
map.put(field.getName(), (String) field.get(ConstClass.class));
}
}
}
That you get in map all fields containing static String.
How will I be able to retrieve the value of a variable which has a dynamic name
For Example I have list of constants
public class Constant{
public static final String S_R = "Standard(240)";
public static final String S_W = "Standard(180)";
public static final String L_R = "Large(360)";
public static final String L_W = "Large(280)";
}
Based on database I build a variable name
String varName = "S" + "_" +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.
You can use a Map<String, String> and locate the value by its key.
Even better, you can have an enum:
public enum Foo {
S_R("Standard", 240),
S_W("Standard", 180),...;
private String type;
private String duration;
// constructor and getters
}
And then call Foo.valueOf(name)
(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)
If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.