I'm getting a list of organization type and code are stored as labelvaluebean as below:
[LabelValueBean[ORG1, XX], [ORG2, AA]] - in array.
later these values are stored in a session variable. My question is, is there a way I can search thru this array to match the name and get the code ? (for ex: match with ORG1 and get XX). If user enter ORG1, I should send XX to back-end.
This sounds like you want to be using a Map instead of an array. A Map will store...mappings...between keys and values - think of it like a table with 2 columns, where the first column is your organization type and the second column is the code. You then take an organization code, look in your table at the values in the first column until you find a match, then you look over at the second column for the code, and return it. Obviously, this is handled by the Map implementation used, so all you need to do is declare what Objects should be used as the keys and values. In your case, maybe you'll have a Map<String, String>.
For example,
Map<String, String> map = new HashMap<String, String>();
map.put("ORG1", "XX");
map.put("ORG2", "AA");
map.get("ORG1") // returns "XX"
map.get("ORG2") // returns "AA"
Related
I have been given an exercise to develop an appropriate data structure to implement a tennis court booking system.
A hashmap is what is required for this and I was given a diagram as a visual representation of the data structure.
From looking at the diagram, I am unclear on how the Key and Value should be defined in the HashMap. Should 'Court' be a class, which is the Key?
For the value, it shows a time, and a players name. How would the value be defined, since it has two values of time and player name?
diagram link
Say we have a HashMap named as "Date1".
Well, now i can put a value with a key in this "Date1" HashMap & later can retrieve that value with the key -> Date1.get("key")
According to your diagram, the keys will be court1, court2, ....
So that, when i will ask for Date1.get("court1"), i can get this ArrayList
But, in this arraylist, each row consist of two values. If our list had one string values in each row, we could say that this is a arraylist of string type.
So lets make our own class (like a type) which can store two values (like "9:00", "player")
public class EntryInfo{
String time, player;
public EntryInfo(String time, String player) {
this.time = time;
this.player = player;
}
}
So if we create an object of "EntryInfo" class, that object will be able to store two values - and each row of our arraylist is of this type.
so, lets sum up :
our hashmap key will be "court1, court2..."
and each key will hold values of ArrayList<EntryInfo> type.
So our hashmap will be like HashMap< String, ArrayList<EntryInfo> >
Now, lets imagine the scenario according to your diagram.
first, lets talk about usage scenario.
Say, there are several courts in your school. They are named as court1, court2, court3, ...
well, I want today's entry-log for court1.
So, i will just ask for feb9.get("court1"), and it will return a list (ArrayList), and i can traverse that array to see the log like following:
for(EntryInfo entryinfo : feb9.get("court1") ) {
System.out.println(entryinfo.time + " : " + entryinfo.player);
}
Yeah, thats it. If i want to get the log for court2, i will retrieve the value using key "court2"
Now, lets discuss how to make this.
well today is feb9, lets make a hashmap to store today's entry log. Lets name the hashmap "feb9"
HashMap<String, ArrayList<EntryInfo>> feb9 = new HashMap<String, ArrayList<EntryInfo>>();
your school has 3 courts. Lets add 3 different keys to this hashmap so that it can hold 3 separate and corresponding entry-logs for each key(court)
feb9.put("court1", new ArrayList<EntryInfo>());
feb9.put("court2", new ArrayList<EntryInfo>());
feb9.put("court3", new ArrayList<EntryInfo>());
You can relate this with creating 3 new files named court1, court2 & court3. Each file consists of an ArrayList object, which is empty for now.
Say, now at 9:00 am, player "zineryt" enters court1. Lets entry the log into our hashmap
feb9.get("court1").add(new EntryInfo("9:00", "zineryt"));
Here feb9.get("court1") will return an ArrayList, and we used add() method to insert elements into the ArrayList.
say, at 9:50am, player "bigboy" enters court1. We can entry the log like below
feb9.get("court1").add(new EntryInfo("9:50", "bigboy"));
and it goes like this.
For tomorrow's information, we will create another new HashMap named feb10 and will follow the same steps.
Date1 (what a name) is a Map<String, Court> of courts by name, like "court1". Court has fields name and a reservation list.
So the key is (probably) a String, and the class itself is the value. One often sees, that the key/ID is also kept in the value class. So a Court object suffices to get its name.
Creating a HashMap for each Date1 is an odd and confusing approach for a HashMap can't really represent a date as we understand it. but given that this is the assignment, you have to keep information about the court number, the playtime and the competitors names. These are at least three fields, if we concat the competitors names to one String.
With only using HashMap you will probably have to use a multi-dimensional HashMap.
HashMap<Integer, HashMap<String, String>> Date1 = new HashMap<String, HashMap<String, String>>();
The outer HashMap holds the court number as the key of type Integer and the pairings as the value of type HashMap.
The inner HashMap holds the playtime as key of type String (though you might as well use the type Time) and the competitors names as value of type String.
When creating this, it is vital to generate addintional accessors to avoid tedious chained calls of Date1.get(someIntVariable).get(someStringOrTime) to receive the players names.
public HashMap<String, String> getPairingsForCourt(int court) {
return Date1.get(court);
}
public String getPlayersForCourtOnTime(int court, String time) {
return getPairingsForCourt(court).get(time);
}
By any chance getting familiar with all the aspects of HashMap requires some time. Especially if you come across mechanisms like keySet() or entrySet(). Have a look on here for a detailed yet understandable start:
A Guide to Java HashMap
I am doing a project for my AP Computer Science class. The current project asks us to create a rip off version of excel that prints to the console. I am wondering if theres a way for me to create an arraylist of empty values that I can assign cell names to (A1, A2, F6, etc.) and then use those names to call values from their place in the arraylist. For example, I'd give the cell D4 a value of 6, store that 6 in an arraylist, then call it back using "D6".
A link to the directions of the project: https://issaquahwednet-my.sharepoint.com/:w:/g/personal/stutlerk_issaquah_wednet_edu/EQOW8BFzHIhIsdvXGP-qKDsBbN7BFa-kUCiMeeq9BZbbwg?e=Nc1Jcs
Maybe I'm not making sense, for which I am very sorry.
//what i would like to be able to do:
arraylist "cells" = (A1 through L20)
user input = "A1 = hi"
set index "A1" of "cells" to "hi"
repeat that stuff until user input = quit
is this possible? or would I just have to create two arraylists, one for cell numbers and one for values? I guess I could do that and then if a user wants to see what a cell says then they could Say "A1" and I could search my cell arraylist for a value of A1 then compare that index with the other arraylist.
I'm completely lost one this and, again, sorry if I'm not making any sense.
To do what you want, you'd need a map rather than a list. Lists always have integer numbers as the indices and there's no way to change that. (You could technically do this with two arrayLists, but it would be a pain to maintain it so that "A1" and "hi" stayed in the same index on two different lists if you ever had to delete/move anything.)
The HashMap documentation is here: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
And you'd do something like this:
Map<String, String> cells = new HashMap<String,String>();
cells.put("A1", "hi");
That would create a key-value pair with key "A1" and value "hi".
You can use structure map where for every key you have associated a value.
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
EDIT: I have three maps with following format:
map1.put("aaa",1);
map1.put("bbb",1);
map1.put("ccc",1);
map2.put("aaa",2);
map2.put("bbb",3);
map3.put("ccc",6);
map3.put("ddd",6);
Now I want the result as list with following format:
[{"id":"aaa","map1count":"1","map2count":"2","map3count":"0"},
{"id":"bbb","map1count":"1","map2count":"0","map3count":"0"},
{"id":"ccc","map1count":"1","map2count":"0","map3count":"6"},
{"id":"ddd","map1count":"0","map2count":"0","map3count":"6"}]
How can I do this in java, help me to figure out.
you can create a class Count, with three members ex. mapCount1, mapCount2, mapCount3. Now create result map
HashMap<String, Count>() result = new HashMap<>();
Now you need to traverse these 3 maps, check map.containsKey(key), here key might be "aaa", "bbb", "ccc" etc. Now traverse first map, since map doesnt not contain any key, add key with value to result map. Now do this for 2nd, 3rd map, If key is there and then get value of count object and update count for mapCount2/3. At last for each key you can print count specific to each map.
This question already has answers here:
How to implement a Map with multiple keys? [duplicate]
(27 answers)
Closed 7 years ago.
I have to choose one data structure for my need below i am explaining the conditions there are following values
abc,def,rty,ytr,dft which all are map to row R1B1 (actully key is combination of R1+B1)
abEERc,dFFFef,rGGty which all are map to row R1B1 (actully key is combination of R1+B2)
KEY VALUE
abc,def,rty,ytr,dft ---> R1B1
abEERc,dFFFef,rGGty ---> R1B2
now for example lets say if i get ytr then i would be able to retrieve R1B1
or lets say i get the value rGGty then i would be able to retrieve R1B2
now the case is that matters is of search , complexity and the time taken as the things have to go in sequence
for example it will first pick the first line to search ytr , it will first match it with abc which will not match then will have to match with def it will not again match then it will match with rty which will not also match then it will finally match with ytr and finally it will find the key R1B1 finally
similarly if the second string need to be searched lets say rGGty then it would scan first row in which it will not find the value then search would continue to second row and also in second row in the third element it would get rGGty as element then it would retrieve R1B2 as value
lets say if put this thing in map then a sequence search will go on key and then only we will be able to find the corresponding value ,
Folks please advise which will be the best data structure i can implement in java in which i will have to search the keys items to find the corresponding value in very fast time also which will not hit the performance too
Folks please advise which will be the best data structure to obtain this functionality itself
I would use a Map. For the map entry, the key would be the matching sequence (abc) and the key would be the appropriate value (R1B1).
The same value can be placed in the map multiple times.
EDIT: Example
// Populating the search map
Value r1 = Value("r1");
Value b1 = Value("b1");
Value b2 = Value("b2");
MultiPartValue r1b1 = new MultiPartValue(r1, b1);
MultiPartValue r1b2 = new MultiPartValue(r1, b2);
Map<String, MultiPartValue> searchMap = new HashMap<>();
searchMap.add("abc", r1b1);
searchMap.add("def", r1b1);
searchMap.add("rty", r1b1);
searchMap.add("ytr", r1b1);
searchMap.add("dft", r1b1);
searchMap.add("abEERc", r1b2);
searchMap.add("dFFFef", r1b2);
searchMap.add("rGGty", r1b2);
// Using the search map
String searchText = "ytr";
MultiPartValue matchingValue = searchMap.get(searchText); // matchingValue = r1b1
The keys looked to me to be Strings; but the values R1B1 and R1B2 did not.
The classes MultiPartValue and Value are my modelling of your combinations of R1B1 and R1B2. Use what ever is appropriate for you use case. They could be Strings if that is appropraite.
I guess you can use LinkedHashMap and once you insert the data it may look like as follows.
KEY VALUE
abc R1B1
def R1B1
rty R1B1
ytr R1B1
dft R1B1
abEERc R1B2
dFFFef R1B2
rGGty R1B2
First, my code works fine. Nothing needs to be done, but as I copied some parts of the code from somewhere else, I dont fully understand whats happening here and hope for an explanation to learn something.
I use the play framework and send my controller class an AJAX POST with an ID and a score. I put those parameters into strings and save them in my DB.
Map<String, String[]> parameters = request().body().asFormUrlEncoded();
String questionIDInput = parameters.get("questionID")[0];
String voteScoreInput = parameters.get("score")[0];
The part I dont get is this: .get("questionID")[0]; / .get("score")[0];.
Why are the two zeros in there? Is the map some sort of a long String and I am using "questionID / score" as a key to find the values? The 0 really confuses me, enlighten me please.
parameters.get("questionID") returns the value for the key "questionID". The value is a String array (String[]), so parameters.get("questionID")[0] gives you the first String of that array.
Note that this code assumes that the "questionID" key is present in the Map and that the value for that key is a non empty array. If any of those assumptions would turn out to be false, you'll get a NullPointerException or ArrayIndexOutOfBoundsException.
The Map has a key and a value that corresponds to the key.
In your map, the key is of type String, whereas the value is of type String[] (an array of String object).
When you do parameters.get("questionID"), this will fetch the String[] array which corresponds to the key with value equal to "questionId".
In order to get the first element of the returned array, [0] is used.