Adding n number of values to hashmap - android

In arrayList I can add n number of values like the below code
RowOneCollection = new ArrayList<Button>((Arrays.asList(btn1,btn2,btn3,btn4)));
Similarly in hash map I am adding n number of vales like this
Map<String, String>map= new HashMap<String, String>();
map.put("bi","biology");
map.put("ma","maths");
like this I am adding n number of values.How I can add all the values in single line like the arraylist

You can put the data using For loop if you have 2 String arrays consisting of Keys and Values.
String[] keys = {"a","aa","aaa"}; //keep both array of same size.
String[] values = {"a1","aa2","aaa3"};
Map<String, String> map = new HashMap<String, String>();
for(int i = 0 ; i < keys.length; i++)
{
map.put(kays[i], values[i]);
}
Hope this helps.

You probably want to adjust how you are populating your HashMap as follows:
HashMap<String,xyz> hMap=new HashMap<String,xyz>();
for(int i=0;i<list.size();i++)
{
hMap.put("Data"+i, list);
}
Where xyz is the object, that you are working with. This approach allows you to take advantage of Java's Generics capability in its Collection objects such as HashMap.

Related

How to separate array list value with comma and put in hashmap

I have this kind of data in sessionList
Now I want to run a loop and put this data inside hashmap i.e. key and value pair because I then want to post hashmap data to URL so I need all the values from session list to be mapped in a hashmap
I tried with something like this but it doesn't work.
Map<String, String> stringMap = new HashMap<>();
for (int count = 0; count < sessionList.size(); count++) {
stringMap.put("booking_session[sessions]["+date+"][game_session]
[" + count+"]", sessionList.get(count).split(",")[0]
}
As you can see I am putting some string values in string map with 'date' and count values as variables so that the retrieved value can be filled in it. This 'date' value should be filled by the sessionList data that is before the comma and this line 'sessionList.get(count).split(",")[0]' should be filled with sessionList data after comma i.e. the time session value.
So basically the conclusion is:
1- SessionList data before comma at all indexes should be filled in 'date' variable and data after comma at all indexes should be filled in 'value' field of the hashmap. How can I achieve that? Please Help
Although your code is working for most of the case, please check the below solution.
Map<String, String> stringMap = new HashMap<>();
for (int count = 0; count < sessionList.size(); count++) {
stringMap.put("booking_session[sessions][" + sessionList.get(count).split(",")[0] + "][game_session] [" + count + "]", sessionList.get(count).split(",")[1]);
}
OR
Map<String, String> stringMap = new HashMap<>();
for (int count = 0; count < sessionList.size(); count++) {
String[] result = sessionList.get(count).split(",");
stringMap.put(result[0], result[1]);
}

How I can convert the hashmap to array?

I want hashmap to array
I create the hashmap
Map<Integer,File> selectedFiles = new Hashmap<>();
and put it some Map data
And I convert this hashmap's values to array so
File[] files = (File[]) selectedFiles.values().toArray();
But errors occur;
java.lang.Object[] cannot be cast to java.io.File[]
I know that when I want the hashmap's values to array, use .values.toArray() but maybe it is not corret;
This way is wrong?
Map<Integer, File> selectedFiles = new HashMap<>();
selectedFiles.put(1, null);
File[] files = selectedFiles.values().toArray(
new File[selectedFiles.size()]);
System.out.println(files);// We will get the object [Ljava.io.File;#15db9742
arrays. toArray without parameters creates an object array because the type information of the list is lost at runtime.
Please use below Code to convert HashMap to Array ,You can change String to File in your case.
//Creating a HashMap object
HashMap<String, String> map = new HashMap<String, String>();
//Getting Collection of values from HashMap
Collection<String> values = map.values();
//Creating an ArrayList of values
ArrayList<String> listOfValues = new ArrayList<String>(values);
// Convert ArrayList to Array
String stringArray[]=listOfValues.toArray(new String[listOfValues.size()])

To remove key from hashmap and rearrange keys when used in recycler view

Please any one can help how to remove particular key from hashmap and then rearrange the keys in hashmap accordingly.
Below is my code.
Set<Integer> integerSet = hashMap.keySet();
int removekey = pos;
ArrayList<Integer> integers = new ArrayList<>();
for (Integer integer : integerSet) {
if (integer > removekey) {
integers.add(integer);
}
}
for (Integer integer : integers) {
if (hashMap.containsKey(integer)) {
AddCardPojo pojo = hashMap.get(integer);
pojo.setImagCard(cardImage[integer - 1]);
hashMap.remove(integer);
hashMap.put(integer - 1, pojo);
}
}[![enter image description here][1]][1]
I have attached screenshot of error
You can directly remove a key value pair,you can directly do
hashMap.remove(removeKey);
as for 're arranging keys in hashmap',
it is a data structure which makes no guarantees of order of data.
Check this answer for more
If you need a particular order as per integer, you could use arraylist
Finally it could be done.
Below is my answer.
hashMap.remove(key);
List<AddCardPojo> hashMapsList=new ArrayList<>();
Iterator it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
hashMapsList.add((AddCardPojo) pair.getValue());
}
hashMap = new HashMap<>();
for(int i=0; i<hashMapsList.size();i++){
hashMap.put(i,hashMapsList.get(i));
}

Looping with while loop while fetching records from database is not working properly

Im trying to iterate two arrays simultaneously as follows,
First if countriesIterator has got next element, domain Iterator will be looped.
CountryIterator has got two elements and domain iterator might contain n elements.
when Im looping the domainIterator, Im populating an arraylist with values that I have looped.
and when the loop reaches the country iterator, Im putting the arraylist within a hashmap.
Iterator<String> domainIterator = selectedDomains.iterator();
Iterator<String> countriesIterator = selectedCountries.iterator();
filteredComplianceCount = new ArrayList<Integer>();
inProgressComplianceCount = new ArrayList<Integer>();
delayedComplianceCount = new ArrayList<Integer>();
nonComplianceCount = new ArrayList<Integer>();
//Looping Countries
while (countriesIterator.hasNext()) {
String countryKey = countriesIterator.next();
Country country = aparjithaDb.getCountryId(countryKey);
//Looping Domains
while (domainIterator.hasNext()) {
Domain domain = aparjithaDb.getDomain(domainIterator.next());
int domainId = domain.getDomainId();
int countryId = country.getCountryId();
//fetch datas from db based on country and domain id/
List<ChartData> allChartCDCounts = db.getAllChartCDCounts(countryId, domainId);
//iterate the list to get the count values
for (ChartData al : allChartCDCounts) {
int complied_count = al.getComplied_count();
int delayed_compliance_count = al.getDelayed_compliance_count();
int not_complied_count = al.getNot_complied_count();
int inprogress_compliance_count = al.getInprogress_compliance_count();
//add the count values to an arraylist
filteredComplianceCount.add(complied_count);
delayedComplianceCount.add(delayed_compliance_count);
inProgressComplianceCount.add(inprogress_compliance_count);
nonComplianceCount.add(not_complied_count);
}
}
//put the arraylist with in hashmap
compMap.put(countryKey, filteredComplianceCount);
delayedCompMap.put(countryKey, delayedComplianceCount);
inProgMap.put(countryKey, inProgressComplianceCount);
nonCompMap.put(countryKey, nonComplianceCount);
}
The problem with my code is that, the key of hashmap remains unique (The keys are two different country names after adding values) but the values remains the same for both keys. The domain Iterator is being invoked only once but it should have been invoked twice because there are two different keys. How can I sort this out?
by the first iteration of countriesIterator you have your domainIterator reached the end. You probably should include your Iterator<String> domainIterator = selectedDomains.iterator(); into countriesIterator loop so it started to iterate again from the beginning on the each iteration of countriesIterator.

Android storing arraylist data into multimap using same key

Hi friends i got stucked into these problem at the last stage of my program.Here is some description about my project:i am calling a web service with the help of Ksoap and getting the JSON response from the server than,i am parsed that response and store it into the correspondent arraylist.Till here everything is working fine.Now the problem starts here i want to store all these AppID,AppName,AppTabID,Icon,Tabname into a multimap with same key for the same index.How can i achieve that ?Any help would highly appreciated!
private SoapPrimitive response;
ArrayList<String> AppID = new ArrayList<String>();
ArrayList<String> AppName = new ArrayList<String>();
ArrayList<String> AppTabId = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
ArrayList<Drawable> drawables=new ArrayList<Drawable>();
ArrayList<String> TabName = new ArrayList<String>();
<!--here are the Arraylist declaration->
public String parse(String a) throws Exception {
JSONArray jsonArry1 = new JSONArray(res); // create a json object from a string
// JSONArray jsonEvents = jsonObj.optJSONArray("AppItems"); // get all events as json objects from AppItems array
System.out.println("Length of array for AppItem tag is.. "+jsonArry1.length());
for(int i = 0; i < jsonArry1.length(); i++){
JSONObject event = jsonArry1.getJSONObject(i); // create a single event jsonObject
String AppID=event.getString("AppId");
System.out.println("AppId is "+AppID);
String AppName=event.getString("AppName");
System.out.println("AppName is "+AppName);
String AppTabId=event.getString("AppTabId");
System.out.println("AppTabId is "+AppTabId);
String Icon=event.getString("Icon");
System.out.println("Icon is "+Icon);
TabHtml=event.getString("TabHtml");
System.out.println("TabHtml = "+TabHtml);
}
System.out.println("return"+TabHtml);
return TabHtml;
}
the above code i am using for saving all the content into arraylist object.From here i want to set all these diferent Arraylist into same MultiMap.How can i achieve that?
I'd just define an AppData container class to hold all data related to a single response, and then just put AppData objects into your multimap.
On this link (Java Map Interface) search for multimap which gives a straight forward implementation of a multimap.
However from what I understand of your question, you'll have to put all your Lists into a List and that would go into a MultiMap (which will just be a HashMap<String,ArrayList<ArrayList>>).
It is not very good approach to have all these different lists for different fields in response, but as you have implemented almost completed, I would lead this approach further:
You can have a Map into map to resolve this prob:
All you need to have follow the below loop:
HashMap<Integer, HashMap<String, String> parsed=new HashMap<Integer, HashMap<String, String>();
for(int i=0;i<AppID.size();i++)
{
HashMap<String, String> keyValues= new HashMap<String, String>();
keyValues.put("id", AppName .get(0));
keyValues.put("id", AppTabId .get(0));
keyValues.put("id", Icon .get(0));
.....
parsed(new Integer(i), keyValues);
}

Categories

Resources