Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.
Related
I wonder how to make a registry/database list in Java. I mean if I, for example, have a variable called "data", and then I add a new entry to that called "name" with the value "David". Then I would call something like "data.name" to get the value "David".
As seen on this picture
I've been Googling but not finding anything about it.
It sounds like you want a Map from String to String. You can use a HashMap<String,String> for that.
// Create Map using HashMap
Map<String, String> data = new HashMap<String, String>();
// Set name
data.put("name", "David");
// Get name
String name = data.get("name");
System.out.println(name);
A method of mine returns a Map<A,B>. In some clearly identified cases, the map only contains one key-value pair, effectively only being a wrapper for the two objects.
Is there an efficient / elegant / clear way to access both the key and the value? It seems overkill to iterate over the one-element entry set. I'm looking for somehing that would lower the brain power required for people who will maintain this, along the lines of:
(...)
// Only one result.
else {
A leKey = map.getKey(whicheverYouWantThereIsOnlyOne); // Is there something like this?
B leValue = map.get(leKey); // This actually exists. Any Daft Punk reference was non-intentional.
}
Edit: I ended up going with #akoskm solution's below. In the end, the only satisfying way of doing this without iteration was with a TreeMap, and the overhead made that unreasonable.
It turns out there is not always a silver bullet, especially as this would be a very small rabbit to kill with it.
If you need both key/value then try something like this:
Entry<Long, AccessPermission> onlyEntry = map.entrySet().iterator().next();
onlyEntry.getKey();
onlyEntry.getValue();
You can use TreeMap or ConcurrentSkipListMap.
TreeMap<String, String> myMap = new TreeMap<String, String>();
String firstKey = myMap.firstEntry().getKey();
String firstValue = myMap.firstEntry().getValue();
Another way to use this:
String firstKey = myMap.firstKey();
String firstValue = myMap.get(myMap.firstKey());
This can work as an alternate solution.
There is a method called keySet() to get set of keys. read this thread.
else {
A leKey=map.keySet().iterator().next();
B leValue; = map.get(leKey); // This actually exists. Any Daft Punk reference was non-intentional.
}
Using for-each loop and var :
for(var entry : map.entrySet()){
A key = entry.getKey();
B value = entry.getValue();
}
mongodb query is db.test.find({"col1":{"$ne":""}}).count(), I have tried many sources to find the solution, the "col1" must be populated from list array, please help me
I have pasted a part of my code
`
List<String> likey = new ArrayList<String>();
for (DBObject o : out.results())
{
likey.add(o.get("_id").toString());
}
Iterator<String>itkey = likey.iterator();
DBCursor cursor ;
//cursor = table.find();
HashMap<String, String> hashmap = new HashMap<String, String>();
while (itkey.hasNext())
{
System.out.println((String)itkey.next());
String keys = itkey.next().toString();
//System.out.println("keys --> "+keys);
String nullvalue = "";
Boolean listone = table.distinct(keys).contains(nullvalue);
hashmap.put(keys, listone.toString());
//System.out.println("distinct --> "+keys+" "+listone);
//System.out.println("proper str --- >"+ '"'+keys+'"');
}
Iterator<String> keyIterator = hashmap.keySet().iterator();
Iterator<String> valueIterator = hashmap.values().iterator();
while (keyIterator.hasNext()) {
//System.out.println("key: " + keyIterator.next());
while (valueIterator.hasNext()) {
//System.out.println("value: " + valueIterator.next());
//System.out.println("Key: " + keyIterator.next() +""+"value: "+valueIterator.next());
String hashkey = valueIterator.next();
}
}
`
When you post code, it helps if you indent it, so it is more readable. As I mentioned to you on another forum, you need to go back and review the Java collection classes, since you have multiple usage errors in the above code.
Here are a few things you need to do to clean up your code:
1) You don't need to use the itkey iterator. Instead, use:
for (String key : likey)
and get rid of all the itkey.next calls. Your current code only processes every second element of the List. The other ones are printed out.
2) Your HashMap will map a key to a Boolean. Is that what you want? You said you want to count the number of non-zero values for the key. So, the line:
Boolean listone = table.distinct(keys).contains(nullvalue);
is almost certainly in error.
3) When you iterate over the HashMap, you don't need the valueIterator. Instead, get the key (either from the keyIterator, or a variable you define using the simpler iterator syntax above), then use the key to get the matching value using hashmap.get(key).
This will not make your code work, but it will clean it up somewhat - at the moment it is difficult to understand what you are intending it to do.
I have a method that read from database and get some string there. According what I get I will override that string for another that I already know. For example:
str → string
bin → binary
and so on..
My question is, what is the best practice for doing this? Of course I already thought about if's...
if (str.equals("str"))
str = "string";
A file that have this things pre-defined, a multi-dimensional array, etc.. But this all seems a quite newbie, so what do you recommend? What is the best way?
Use a Map:
// create a map that maps abbreviated strings to their replacement text
Map<String, String> abbreviationMap = new HashMap<String, String>();
// populate the map with some values
abbreviationMap.put("str", "string");
abbreviationMap.put("bin", "binary");
abbreviationMap.put("txt", "text");
// get a string from the database and replace it with the value from the map
String fromDB = // get string from database
String fullText = abbreviationMap.get(fromDB);
You can read more about Maps here.
You could use a map, for example:
Map<String, String> map = new HashMap<String, String>();
map.put("str", "string");
map.put("bin", "binary");
// ...
String input = ...;
String output = map.get(input); // this could be null, if it doesn't exist in the map
Map is a good option as people have suggested. The other option which I normally consider in this scenario is Enum. It gives you an additional capability of adding behavior for a combination.
I am trying to access a String array which i have created in my Java class.
The string array is stored in a Map with the name 'notSelected' using the same key.
I also have a single String object called 'testString' stored in the same Map which i can easily access and display using:
$testString
However how do i go about accessing the String array object (notSelected) from the Map inside the velocity template object?
I have tried:
$notSelected.get(0)
$notSelected[0]
$notSelected.[0]
${notSelected}.get(0)
The last three seem to return the reference value of the memory location of the String array object but i still can't access the values inside the array.
Any help is gladly appreciated. Thanks
Here is the java code:
public Map<String, Object> getVelocityParameters
(final Issue issue, final CustomField field, final FieldLayoutItem fieldLayoutItem) {
final Map<String, Object> map = super.getVelocityParameters(issue, field, fieldLayoutItem);
String[] notSelected = {"foo", "bar", "baz"};
map.put("notSelected", notSelected);
String[] selected = {"foo", "bar", "baz"};
map.put("selected", selected);
//this code works and i can access $testString in the velocity template
String testString = "Test Worked";
map.put("testString", testString);
return map;
}
JIRA uses an older version of Velocity that does not support array index notation for accessing arrays. Instead, use a List and .get(n) notation:
List foo = new ArrayList() {{ add("hi"); add("there"); }};
$foo.get(0)
$foo.get(1)
And remember, little tidbits of info like the environment you're operating in can make a huge difference (and when someone asks a question, there may be a reason for asking it ;)