Comparing java variables and printing - java

Suppose , I have some variables as :
String x="abcd";
String y="qwert";
String z="mnvji";
and more...
I take an input from user.
If user inputs 'x' , I print that string i.e. I print "abcd"
If user inputs 'y' , I print "qwert" and so on...
Is there any way to do it without switches or ifs??
Thank you,friends, in advance.

You could create a map from input string to result. Initialize the map:
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
And when you want to print the result from the input from the user:
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));

Local variable names aren't available at runtime and reading field knowing it's name requires some reflection (see #amit's answer). You need a map:
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Now just take value from that map:
String value = map.get(userInput);
value will be null if it doesn't match any of x/y/z.

As we can approach like that also,
String input[]=new String['z'];
input['X']="abcd";
input['Y']="qwert";
input['Z']="mnvji";
System.out.println(input['X']);
But it will come under some limitation

Map collection using key value pair implementation solve your problem .
put varible x,y,z as key and "abcd" ,.. as value.
Retrieve value from specific key according to input value.
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
to get value
String value = map .get(inputValue).

Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
will probably work.

Put your variable set into a HashMap as (key,value) pairs and just retrieve the value for the particular key when user inputs the key.

create an string array in which x,y,z should be indexes and store the content relatively ...
get the user input and pass it to the array as index ..you will get it..

If you really don't want to use switches or ifs (and I'd assume you include maps in that) then you'd have to use reflection to get the names of all the variables and decide which to print on them. Here's the basics:
Class yourClass = Class.forName("yourpackagename.YourClassName")
Field[] allFields = yourClass.getDeclaredFields();
String[] fieldNames = new String[allFields.length];
for(int i = 0; i < fieldNames.length; i++)
{
fieldNames[i] = allFields [i].getName();
}
//Get name of field user wants to display, and look it up in
//the fieldNames array to get the index of it, store this index
Object instance = yourClass.newInstance();
System.out.println(allFields[indexToDisplay].get(instance));
Of course, this could well be overkill.

If you have no choice but using object variables (fields) and not a Map as suggested by other answers - you might want to use reflection, and specifically the Class.getField() and Class.getDeclaredField() methods-
Field f = MyClass.class.getDeclaredField("x");
System.out.println(f.get(myObject));
Where MyClass is your class name and myObject is the object you want the value from.
Note that with this approach - you cannot add fields - you can only get existing ones.

Related

use reflection to set or get array in a Java Map

Is there a way to get or set an array element stored in a Java Map?
Example:
If we have a map like this:
{
name: "Blah",
friends: ["Foo", "Bar"]
}
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
myMap.put("name", "Blah");
myMap.put("friends", friends);
Is it possible to use Reflection to get or set the first element in the friends array in the "myMap" from the string: "myMap.friends[0]"
Your question is not very clearly written and I believe that's why you are not getting the answer you expect but, If I understood your question correctly, you need to parse the following input string at runtime that you don't know beforehand:
myMap.friends[0]
And this should be parsed into components like:
mapName = "myMap"
mapKey = "friends"
valueIndex = 0
And with this information, you need to manipulate data in a Map at runtime through reflection.
Note: This only makes sense if you could potentially have more complex expressions, using different sort of objects and accessing nested properties of retrieved objects, otherwise you wouldn't need reflection at all.
Note 2: You may want to have a look at JXPath which already does a lot of this for you based on a XPath-like syntax for navigating object graphs.
That said, if my assumptions are correct and you still want to do it yourself, consider the following example.
For the sake of demonstration, let's consider our map is returned by a method myMap inside a Context.
private static class Context {
public Map<String, Object> myMap() {
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
friends.add("Foo");
friends.add("Bar");
myMap.put("name", "Blah");
myMap.put("friends", friends);
return myMap;
}
}
I'm assuming you are already parsing the input string into the different components. If not, for this simple string you could do it with simple regular expressions. If you already have the components, let's consider the following method:
public static Object readContextMap(Context context,
String mapName, String mapKey, Integer mapValueIndex) throws Exception {
// gets Context class for inspection
Class<?> cls = context.getClass();
// search for a method based on supplied mapName
Method mapMethod = cls.getDeclaredMethod(mapName);
// get a value from the retrieved map based on mapKey
Object mapValue = mapMethod.getReturnType()
.getDeclaredMethod("get", Object.class)
.invoke(mapMethod.invoke(context), mapKey);
// if the result is of type list, use the index to return the indexed element
if (List.class.isAssignableFrom(mapValue.getClass())) {
return ((List<?>)mapValue).get(mapValueIndex);
}
// otherwise return the object itself
return mapValue;
}
For testing purposes, consider the following main method:
public static void main(String[] args) throws Exception {
Context context = new Context();
String input = "myMap.friends[0]";
// parse input into...
String mapName = "myMap";
String mapKey = "friends";
Integer valueIndex = 0;
Object firstFriend = readContextMap(context, mapName, mapKey, valueIndex);
System.out.println(firstFriend);
// prints Foo
Object name = readContextMap(context, "myMap", "name", null);
System.out.println(name);
// prints Blah
}
This should be approximately what you want. You can easily create variations of this to set values as well. Please bear in mind that this code is just for demo purposes and needs a better error handling (e.g. verify if the context is really returning a map and nothing else).
This should be something along the lines you are looking for.
There's no need to use reflection here. You can simply cast it (which is also unsafe, but less so).
You can just do this:
List<String> friends = (List<String>) myMap.get("friends");
friends.set(0, "Bob");

How to get values from #result-set-1 in SimpleJdbcCall

When executing SimpleJdbcCall, I get two parameters #result-set-1, #update-count-1
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("name", "something");
Map<String, Object> resultFromProcedure = cstmt.execute(parameterSource);
#result-set-1 have variables
[{
id = 123,
name = "something",
accountnumber = 123456,
balance = 789999
}]
Everything is fine until I tried to access
resultFromProcedure.get("accountnumber")
Which getting null. The Question is how to access the values in #result-set-1
If I understand this correctly; Map<String, Object> resultFromProcedure consist of 2 entries having keys #result-set-1 and #update-count-1.
And the object of #result-set-1 is an object having 4 member variables. (If it is a String, then you'd need to convert the Json to a Java Object (Example))
Thus your call to resultFromProcedure.get("accountnumber") is trying to fetch an object using the key accountnumber, but the map doesn't contain that key. You need to first get the object for #result-set-1 e.g.
SomeDTO someDTO = resultFromProcedure.get("#result-set-1");
Then you can call
someDTO.getAccountNumber();
As there could be more than one result set, SimpleJdbcCall returns an object in the arraylist within another map marked as "#result-set-1". To access the values in it, try the following:
ArrayList arrayList = new ArrayList();
arrayList = (ArrayList) resultFromProcedure.get("#result-set-1");
Map resultMap = (Map) arrayList.get(0);
System.out.println("Account Number: " + resultMap.get("accountnumber"));

Arraylist - String/Double

I am taking a basic objects first with java class, i don't know much yet and need a little help ..
I need to assign these values to an arraylist but also need to allow the user to choose a health option based on a string that will then output the value related to the option..
double [] healthBenDesig = new double [5];
double [] healthBenDesig = {0.00, 311.87, 592.56, 717.30, 882.60};
Strings I want to assign are:
none = 0.00
employeeOnly = 311.87
spouse = 592.56
children = 717.30
kids = 882.60
Ultimately, I want the user to input for example "none" and the output will relate none to the value held in the arraylist [0] slot and return that value. Is this possible? Or is there an easier way I am overlooking?
if anyone could help me out I would really appreciate it :)
Thanks
Yes. This is possible with HashMap.
HashMap<String,Double> healthMap = new HashMap<String,Double>();
healthMap.put("none",0.00);
healthMap.put("employeeOnly",311.87);
healthMap.put("spouse",592.56);
healthMap.put("children",717.30);
healthMap.put("kids",882.60);
Now, when user enters none then use get() method on healthMap to get the value.
For safety check that key exists in map using containsKey() method.
if(healthMap.containsKey("none")) {
Double healthVal = healthMap.get("none"); //it will return Double value
} else {
//show you have entered wrong input
}
See also
HashMap oracle docs
Best solution is Map<String, Double>.
Map<String,Double> map=new HashMap<>();
map.put("none",0.0);
Now when you want the value for "none" you can use get() method
map.get("none") // will return 0.0
Here's something for you to get started with since it's the assignment:
Create a Map<String, Double> that holds the number and string as key/value pair.
Store the above values into the map
When a user enters the input, capture it using Scanner
Do something like this.
if(map.containsKey(input)) {
value = map.get(input);
}
Use Map Inteface
Map<String, Double> healthBenDesig =new HashMap<String, Double>();
healthBenDesig.put("none", 0.00);
healthBenDesig.put("employeeOnly", 311.87);
healthBenDesig.put("spouse", 592.56);
healthBenDesig.put("children", 717.30);
healthBenDesig.put("kids", 882.60);
System.out.println(healthBenDesig);
OutPut
{
none = 0.0,
spouse = 592.56,
children = 717.3,
kids = 882.6,
employeeOnly = 311.87
}

Getting values in hash map in Java

I am not a java developer, and this is not my homework or something. I am just in need of getting the values of these parameters: end & begin. this is what I have:
rs = [{}, {end=2013/11/5, begin=2012/11/6}]
I am wonder if I could get values like this:
rs[1].end
rs[1].begin
the source is:
protected QueryParameters prepareForm(final ActionContext context) {
final SearchErrorLogForm form = context.getForm();
Map<String, Object> rs = form.getValues();
System.out.println(rs);
/*the output is: {pageParameters={}, period={end=2013/11/5, begin=2013/11/6}} */
}
sorry, the rs type is hashmap.
That is not a valid statement.
A proper way of assigning an array would be:
String dates[] = {"2013/11/5","2012/11/6"};
String start = dates[0];
String end = dates[1];
There is a excellent tutourial at oracle docs
Okay, that is a Map containing two Maps as it seems. The first map named "pageParameters" is empty. The second one is named period and contains two items. The key "end" maps to the value "2013/11/5". The key "begin" maps to the value "2013/11/6".
To access the objects in the map you could do like this:
final Map<String, String> period = (Map<String, String>) rs.get("period");
final String begin = period.get("begin");
final String end = period.get("end");
If you would like to change a value in the map period you will need to overwrite the already existing one:
period.put("end", "NEW_END");
rs.put("period", period);
For further information, Oracle has great tutorials on Hashmaps.
you can do like following:
rs[1][0] for the first
rs[1][rs[1].length-1] for the last

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Categories

Resources