How to retrieve value from Map<ArrayList<String>, Object> - java

I want to know how can I retrieve values from Map<ArrayList<String>, Object> Where the String and object are stored as Array [] for user define length.
Here is an Example:
int counter=0, n=0;
if (dataSnapshot.exists()){
for (DataSnapshot ds: dataSnapshot.getChildren()){
loca[counter]= new ArrayList<>();
itemListProduct[n]= new ItemListProduct();
itemListProduct[n]= ds.getValue(ItemListProduct.class);
loca[counter].add(testHeaderlist.get(counter));
System.out.println(ds.child("item_NAME").getValue(String.class));
objectMap.put(loca[counter],itemListProduct[n]);
counter++;
}
Here the testHeaderlist is an ArrayList<String> where there are some string stored.
I wanted to store data in the below Image manner:
So now my question is how can I retrieve the Key as well as the Object from "dataList". As from the code which I have shared at the TOP "n" number of list, and the object are stored in the dataList.
The thing is that I want to retrieve to use it in ExpandableListView. loca as header and itemListproduct as my value Object. Where the both are stored at objectMap.
Can anyone please solve it. Thank you!

It is permitted but rather atypical to have an ArrayList as a key to a map. To get the Object you need to do the following:
Object val = map.get(arrayList)
Here, arrayList must contain the exact same strings in the same order as the ArrayList key which refers to the desired object.
Example
Map<List<String>, Integer> map = new HashMap<>();
List<String> key = List.of("abc", "efg");
map.put(key, 20);
Integer v = map.get(List.of("efg","abc")); // different key so
// object not found
System.out.println(v); // prints null
v = map.get(List.of("abc", "efg"));
System.out.println(v); // prints 20
You can get all the Keys of a map by doing
Set<List<String>> set = map.keySet();
You also need to readup on HashMap and ArrayList to understand how they work. The following will keep replacing the object for the key of list[0]
dataList.put(list[0], object[0]);
dataList.put(list[0], object[1]);
dataList.put(list[0], object[2]);
dataList.put(list[0], object[3]);
When the above is done, list[0] will only refer to object[3]

Related

How can I obtain the list of values for a given key and add the list of values to a newly created list?

So I'm going crazy with this one. This is for an assignment and can't seem to get this to work at all!!
I have the following HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team being another class to obtain the details of the teams)
What I need to be able to do is get the List of teams for the Key(String) from the above HashMap, and assign the List to a local variable I have declared:
List<Team> results = teams.get(division);
But this is where I get stuck. I have no idea how I'm suppose to complete this task.
As a further note "division" is the Key used in the HashMap. The ArrayList is a list of teams that belong to the division.
I have tried the below, which does not compile at all. Really not sure how I can get this to work!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**You can ignore the arguments after the "String division". These will be used later.
Iterate over the entrySet() of the Map. Now you can fetch each List for that specific key and proceed further. Something like:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}

Returning entryset in map using key value

I have two string value ID and Value coming from my code, I need to store this in a map without iterating over the map but by checking by the key value if it exists in the map.
The ID can come many times with different value and in that case I have add it to the already existing entry of the ID and add the value along with the existing value
I created a Map with String and List to add the values but I am facing difficulties,
Map < String, List< String >> accessMap = new HashMap < String, List< String>>();
If the key is not present, add a new entry with ID and Value (as List).
How to find the key in the map and get the entrySet without iterating over the map and add the value alone, if the ID is already present in the map.
Example,
while(accessList.hasNext()){
....
....
String id = accessEntry.get(ID);
String value = accessEntry.get(Value);
/*Add the id and value to the map if not present, if ID is present add the *value alone to the entrySet.Value (which is a list)
*/
}
The id and value has to be added into a map checking if the ID is already present in the map, if not create a new entry.
The accessList might have many ID references with different value, in that case the value should be added to the entrySet of the already existing entry, the value would be a list with single value or multiple value.
public static void add(Map<String, Set<String>> map, String key, String value) {
map.compute(key, (id, values) -> {
(values = Optional.ofNullable(values).orElseGet(LinkedHashSet::new)).add(value);
return values;
});
}
For values it is better to use Set to exclude duplications.
Use computeIfAbsent() to initialise a List for the id if one doesn't exist already, then just add the value to that:
entitlementMap.computeIfAbsent(id, s -> new ArrayList<>()).add(value);

Iterate through hash maps and object

I am gradually learning how to use Hashmaps , I have a map where i would be adding
HashMap( student id, other student records as object() ) .
I am trying to retrieve the values with their keys.
Please see below.
HashMap<String, Object> studentinfo = new HashMap<String, Object>();
List<Object> lstObject = new ArrayList<Object>();
studentinfo.put("student height", 5.01); //Put data in studentinfo hashmap
lstObject.add(studentinfo);
// New items hashmap
HashMap<String, Object> items = new HashMap<String, Object>();
//Put object in items hashmap
items.put("student id 001",lstObject); //Store data for 1st id student with 001
items.put("student id 002",lstObject); //Store data for 2nd id student with 002
for (Map.Entry<String, Object> entry : items.entrySet()) {
if(entry.getKey().equals("student id 001")){
//Get student id for only student id 001
System.out.println(entry.getValue());
// When i print this out , this is what i get
// [{student height=5.01}]
}
}
How can i loop thru to get the value only
Like this, for example:
5.01 // Student id 001
To get the value 5.01 which is stored in a map for the key "student height" within a list that is stored in another map under the key "student id 001", you'll need to code the access to that information. The outer map itself only knows of values and if you define the value type to be Object you'd have to cast yourself.
A better design might be to replace that list with a Student object which has a property height and access that.
But just for information, if you'd define your map like Map<String, List<Map<String, Object>> you'd be able to directly access the lists and their elements as values, e.g. (not handling null for simplicity):
Double height = (Double)items.get("student id 001").get(0).get("student height");
Just to reiterate: this is awkward design and should be changed, you'll probably realize that whith increasing experience and knowledge.
Better:
class Student {
double height;
Student(double h) {
height = h;
}
}
Map<String, Student> students = ...;
students.put("student 001", new Student(5.01) );
double height = students.get("student 001").height;
Note that I left out a lot of code for simplicity reasons such as modifiers, getters/setters, null checks etc.
Another note (added here instead of a comment for formatting reasons):
items.put("student id 001",lstObject); //Store data for 1st id student with 001
items.put("student id 002",lstObject); //Store data for 2nd id student with 002
This will put the same list as the value for both keys, i.e. if you change the list elements you'll change it for both student ids.

java list<map> with repeated values

I have a List<Map> which should be of the below syntax:
[{clientName=abcd}, {clientName=defg}]
Previously I had List<Bean> which I want to replace with List<Map>.
Here is my code:
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
What happens with this code is, I am getting [{clientName=defg}, {clientName=defg}] as the output where, clientName=abcd is replaced by the 2nd value defg. How can I get the expected result which is [{clientName=abcd}, {clientName=defg}]?
Thanks
You have to re-initialize your Map<> again before adding to List<> because you are changing previous reference for Map<> object and on same key that will change previous object also.
You code should be :
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap = new HashMap<String,String>(); //Initialize it again.
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
First read up on Map and List. When you add a Map object (or any other object) to a List object, all you're doing is adding a reference to that object in the List.
It means that if you change the Map contents after adding it to the List object, that will be reflected in the List.
In a Map, moreover, the key has to be unique.
So here you need to create a new Map object before you can add the new value and add that new Map object to the list.
See this other post for details:copying a java hashmap
Try below code, Map key should be unique so when you put value to same key n times the value is just replaced for the key, In your code you are replacing the value for same key(clientName) and adding it to list so it is printing the same value which you put in last to map.
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName-1","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName-2","defg");
clientList.add(clientNameMap);

Can a Hash Map have a Key consisting of 2 values?

I have a table consisting 10 columns in database. One of the columns have alphaneumaric values which was set as a key for the hashmap which will have all the values as objects for each row in the hashmap.
example : A10 (key) , rowobj(Class). Now in that same column another value is present as A10. So now if we are trying to load the values to hashmap from the tableas the key name is same will there be multiple values enrolled to that same key name?
Also can we combine the values of 2 columns to create a unique key for the hash map? How to do that?
Thanks
Two options:
create a wrapper object that contains all values as fields, set them, and then map.put(id, rowObject)
use Multimap (guava)
Can't you use primary key of the table as the key of your HashMap ?
You could use a HashMap where the key is still A10 but now the value is a List.
So you could have multiple values for the same key. You only have to pay attention in the insertion that new List is created when the first element is inserted. May be something like (in pseudocode):
HashMap<String, List> myMap = new HashMap<String,List>;
for (elements to insert){
if (!myMap.containsKey(element.key()))
ArrayList myList = new ArrayList();
myList.add(element);
myMap.put(element.key(), myList);
}else{
ArrayList myList = myMap.get(element.key());
myList.add(element);
myMap.put(element.key(), myList);
}
}
If you mean that a Key x should map to a list vals (which are the values that x represents), then that is easily doable like this (didnt check the syntax, so dont expect it to compile):
//assuming that the keys are of type int and values are of type String
Map<int,List<String>> myMap = new HashMap()<int, new ArrayList()<String>>;

Categories