Can anyone help me to iterate on a hash map, and store value to string array?
I have a hash map with two keys and corresponding values under each keys. Since the value set is large, I want to iterate values from hash map for each key and store in to a string array. Please help.
Try this :
List<String> valuesList =new ArrayList<>();
for(String key:mHash.keySet()){
valuesList.add(mHash.get(key));
}
to Strings Array :
String[] stockArr = new String[valuesList.size()];
stockArr = valuesList.toArray(stockArr);
make a new string array of the same size as your hashmap.
loop through your hashmap and assign each iteration to an element in your array.
String[] stringArray = new String[mHashMap.keySet().size()];
int i = 0;
for(String key: mHashMap.keySet()){
stringArray[i] = mHashMap.get(key);
i++;
}
the for loop that i have shown above, and as another also commented can be read as follows:
for(String key : mHashMap.keySet()){
//do this
}
"for all keyStrings in myHashMap.keyStringSet(), do this"
eg. for each item in the hashmap, do whatever is in the brackets.
Your string array is completed.
Related
i have String Array like this:
String[] q1={"AAA-BBB","AAA-CCC","AAA-DDD"}
and i want result like this
temp={"BBB","CCC","DDD"}
i tried below code but the result is wrong
for(int i=0;i<q1.length;i++){
ArrayList<String> temp=new ArrayList<>(Arrays.asList(q1[i].split("AAA-")));
}
Try like this:
ArrayList<String> temp=new ArrayList<>();
for(int i=0;i<q1.length;i++){
String[] array = q1[i].split("-");
temp.add(array[1]);
}
You could use substring:
ArrayList<String> temp = new ArrayList<>();
for(int i=0; i<q1.length; i++){
temp.add(q[i].substring(q[i].indexOf('-') + 1, q[i].length()))
}
you find error Because you use split
Splits this string around matches of the given regular expression.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
q1[i].split("AAA-")
in this line you got 2 result splited 0 = "" AND 1 = "BBB"
so you need to pick the sec result
you have multi Solution
like https://stackoverflow.com/a/50234408/6998825 said
String[] array = q1[i].split("-");
temp.add(array[1]);
//change this q1[i].split("AAA-") to
q1[0].substring(4)
if your AAA- is not going to change
Have you tried creating the ArrayList outside of the loop? As previously you were creating a new ArrayList for every element in your string array
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q1.length;i++){
temp.add(q1[i].substring(4);
}
Assuming that "AAA-" is not going to change.
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));
}
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.
I am receiving the following array values in a for loop:
String[] array1 = new String[""];
BigInteger array2 = new BigInteger[10];
for (int i = 0; i <= count; i++) {
array1[i] //of type string array
array2[i] //of type bigint array
//Now inside same loop i want to store and retrieve those values of array
from shared preferences. Can someone tell me how to store values of array
into preference which are of type String[] and BigInteger[]
}
If you want to store whole array data in shared preferences then you need to take shared preferences key array as same size of your array.
OR
You can append all array data with comma separator in one string object & store in shared preferences and when you get data then split string by comma.
Updated
String[] array1 = new String[10];
StringBuilder array1Data = new StringBuilder();
for (int i = 0; i <= count; i++) {
array1Data.append(array1[i]);
array1Data.append(",");
}
setSharedPreferences("KEY", array1Data.toString()); // Custom method
}
You can use JSONArray array for that. For insert value call array.put(String) or array.put(long). Insert into preferences as String by calling array.toString(). Get from preferences - array = new JSONArray(stringFromPreferences). Get value from array - array.getString(position) and array.getLong(postion).
You can also work with array.put(Object) and (String) array.get(position).
I've been looking for this for a while now, but couldn't find it anywhere in SO or in the docs.
I am using Gson to parse a json file, and suppose the file is:
{
"animal":"cat",
"paws":"4",
"eyes":"2"
}
Now, since all the fields are strings, I want to parse it as an array of strings, I want something like:
{"cat","4","2"}
And I would like to parse the JsonObject regardless of the name of its tags, and that's where the problem lies. I can garantee the json will contain only strings, but I have no clue of what the fields are going to be named.
Anyone ever faced this problem ? Any help is much appreciated, and any research direction also.
Edit
From the anwers, I managed to do it like this:
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
// do your stuff here
}
as explained in this answer
JSONObject has the keys() method that returns an Iterator<String>. Through the iterator you can retrieve the value associated with each key. Here the documentation
EDIT:
Since you are using GSON , you can retrieve the keys through the method entrySet()
You should use Iterator, which you can get by calling .keys() on your JSONObject. I think something like that should work (using org.json library):
String[] output = new String[jsonObject.length()];
Iterator iterator = jsonObject.keys();
int i = 0;
while (iterator.hasNext()){
output[i++] = jsonObject.optString((String) iterator.next());
}
EDIT Ok, in case of GSON it will be like this:
Set<Map.Entry<String, JsonElement>> set = jsonObject.entrySet();
String[] out = new String[set.size()];
int i = 0;
for (Map.Entry<String, JsonElement> x : set){
out[i++] = x.getValue().toString();
}
If you are using gson then simple solution is :
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(YOUR_JSON_STRING, mapType);
// get only values from map
Collection<String> values = map.values();
for (String string : values) {
// do your stuff here
}
result values collection contains
[cat, 4, 2]
JSONObject jsonObject = new JSONObject(parentJson.getJSONObject("objectname")
.toString());
Iterator<?> iter = jsonObject.keys();
while (iter.hasNext()) {
String key =(String) iter.next();
String value = jsonObject.getString(key);
}