How to parse List<Map> in android? - java

Im trying to store data like associative array in JAVA. so i took list with maps
List<Map> processNeedImages = null;
int flag =0;
if(c.moveToFirst()){
do{
Map<String, String> map = null;
map.put("status", c.getString(c.getColumnIndex("system_url")));
processNeedImages.add(flag++, map);
}while(c.moveToNext());
I could not parse this data
List<Map> allImages = getData();
for (Map map:allImages){
Log.d("listImage", String.valueOf(map.get("status")));
}
Even loop is iterating even once.

Initialize all variable in your code like below
List<Map> processNeedImages = new ArrayList<>();
int flag =0;
if(c.moveToFirst()){
do{
Map<String, String> map = new HashMap<>();
map.put("status", c.getString(c.getColumnIndex("system_url")));
processNeedImages.add(flag++, map);
}while(c.moveToNext());
}
this will work fine.
You should read this answer too what is NullPointerException

Map<String, String> map = null
should be replaced with
Map<String, String> map = new HashMap<>();
You are not creating a new map object. Rather you are adding the same map object everytime. although you are adding new values to the map for each cursor position but the object is only one. Hence your loop is going only one time.

Related

How can i convert Map of Strings and Object to a Map of Strings and List

I have method that should return Map<Strings, List<String>> but in the mean time my method gives me a Map<Strings, Object>, I want to transfer the values of object into a List of Strings.
Here is the current code:
#SuppressWarnings("unchecked")
static Map<String, List<String>> getQueryParameters(JsonObject inputJsonObject) {
JsonArray parameters = inputJsonObject.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).findFirst();
Map<String, Object> paramMap = queryParameters.get().getMap();
paramMap contains key and value , values could be an arrays of integers
so I want to put them into the map below:
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
My solution is this which did not work correctly
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
Map<String, Object> paramMap = queryParameters.get().getMap();
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
if (!mystore.containsKey(key)) ;
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
}
I was a key holding another key as value and is just a mix up , any suggestions?
After debuging what happens i see that mystore holds both "key and value" together as a key and value it hold the next "key and value as value
Should be something like this:
while (it.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
String key = next.getKey();
Object value = next.getValue();
if (!mystore.containsKey(key)) mystore.put(key, new LinkedList<String>());
mystore.get(key).add(value.toString());
}
I'm not writing a program for you, but instead help you in finding a problem. You are confused with Entry. If you are using IDE, you should solve it easier. Look for this line :
String key = it.next().toString();
Entry has a K,V pair. The iterator returns an EntrySet and thus usage to get key is it.next().getKey() and it.next().getValue()
Now that you have a correct key, please go on debugging. Instead of putting and getting and manipulating in below lines of your code. Put with correct value instead?
Yours:
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
What about?:
Entry entry = it.next();
//Get key and value here. DO coding using Entry's methods
List<String> ll = new LinkedList<String>();
ll.add(value)
mystore.put(key, ll);
Tip: Always have the Javadoc or reference documentation handy for knowing more. That's how you learn the language. Refer:https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html

android arraylist get hashmap position

I have an ArrayList HashMap like the one below.
ArrayList<HashMap<String, String>> mArrType = new ArrayList<>();
with the following values added into it
HashMap<String, String> map;
map = new HashMap<String, String>();
map.put("type", "TRIMMER");
map.put("request", "5");
map.put("actual", "0");
mArrType.add(map);
map = new HashMap<String, String>();
map.put("type", "HAND ROUTER");
map.put("request", "6");
map.put("actual", "0");
mArrType.add(map);
map = new HashMap<String, String>();
map.put("type", "AIR COMPRESSOR");
map.put("request", "6");
map.put("actual", "0");
mArrType.add(map);
Question is how can i get the position of a hashmap from arraylist. eg : hashmap with 'type' trimmer has a position 0 in arraylist, I want to retrieve the position value "0"
I'll write a small util method
private static int getTrimmerTypeMapPosition(ArrayList<HashMap<String, String>> mArrType) {
for (int i = 0; i < mArrType.size(); i++) {
HashMap<String, String> mp = mArrType.get(i);
if (mp.get("type").equals("TRIMMER")) {
return i;
}
}
return -1;
}
To make this method very generic, have "type" and "TRIMMER" as method params, so that you can just pass any key and value pairs to check with.
That's not efficiently possible with your data structure. You can either store the own position in each HashMap or loop through all entries and search for the one with the type you are looking for.
You can, of course, define another HashMap<String, Integer> which maps all your type strings to the corresponding ArrayList index.
Others answer is also correct, but you can do this thing using Java8 also.
E.g.:
int index = IntStream.range(0, mArrType.size()).
filter(i -> mArrType.get(i).get("type").equals("TRIMMER"))
.findFirst().getAsInt();

Java: Best way to retrieve values in List

I would like to know the best way to retrieve the elements of a list inside a list.
List<Object> totalsList = new ArrayList<Object>();
Map<String, Object> grandTotalsMap = new HashMap<String, Object>();
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
Map<String, String> lineItemsMap1 = new HashMap<String, String>();
lineItemsMap1.put("amount", "$70.00");
lineItemsMap1.put("period", "Monthly");
Map<String, String> lineItemsMap2 = new HashMap<String, String>();
lineItemsMap2.put("amount", "$55.00");
lineItemsMap2.put("period", "Bi-Monthly");
items.add(lineItemsMap1);
items.add(lineItemsMap2);
grandTotalsMap.put("section" , "total per pay period amounts");
grandTotalsMap.put("title", "You'r amount");
grandTotalsMap.put("lineItems", items);
**
// I'm expecting output as: I want to create a new Map and put key-values like below:
{
amount: $70.00,
period: Monthly,
},
{
amount: $55.00,
period: Bi-Monthly,
}
**
In your case, using items.get(int index) will return a HashMap corresponding to the location in the array that map is stored. For instance, items.get(0) would return your the first map you added (lineItemsMap1) while items.get(1) would return the second map you added (lineItemsMap2).
Once you have the correct map you are looking for, you can then call the HashMap.get(String columnName) to retrieve the value you have stored.
Two different ways to access the information stored in your ArrayList are as follows:
HashMap<String, String> map = items.get(0);
String amount = map.get("amount"); // This will return '$70.00'
String period = map.get("period"); // This will return 'Monthly'
OR
String amount = items.get(0).get("amount"); // Returning '$70.00'
String period = items.get(0).get("period"); // Returning 'Monthly'
If you are looking to create a new map with these values, you can either store them in local variables (like done above) and then add the variables into the map when creating it like:
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("newAmount", amount);
Or you can add the values by directly accessing the ArrayList when creating the map:
newMap.put("newAmount", items.get(0).get("amount"));
Hope this helps!

Convert ArrayList to HashMap<String, String>

I have this ArrayList
public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
and I want to convert this to:
HashMap<String, String> comparemap2 = new HashMap<>();
What I want is: I want all the Items inside the ArrayList and want to put them into the HashMap
My HashMap looks like:
KEY VALUE
job_id 032014091029309130921.xml
job_id 201302149014021492929.xml
job_id 203921904901920952099.xml
EDIT:
Later I want to compare this map with an existing map:
Properties properties = new Properties();
try {
properties.load(openFileInput("comparexml.kx_todo"));
} catch (IOException e) {
e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
compareMap.put(key, properties.get(key).toString());
}
HashMap<String, String> oldCompareMap = new HashMap<>();
for (HashMap key : xmlFileNames) {
oldCompareMap.putAll(key);
}
isEqualMaps(oldCompareMap, compareMap);
I only want to compare, if the filename exists in the compareMap. If not, than add it to the xmlFileName Map
I've looked up in StackOverFlow, how I can convert ArrayList to HashMap. But the other Threads treat data types like Item or Product.
I hope you can help me!
Kind Regards
Given...
public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
then something like this should do it.
HashMap<String, String> nhm = new HashMap<>();
for (HashMap xmlFileHm : xmlFileNames ) {
nhm.putAll(xmlFileHm);
}
but be aware if you have duplicate keys in your hashmaps they will get overwritten.
You should also think about coding to interfaces. Take a look at Map and List rather than typing your collections to implementations (ArrayList and HashMap). Take a look at this thread which is quite interesting What does it mean to "program to an interface"?
Depending on what you are trying to do as well you might consider a MultiMap as this might server your purposes better
Edit After update to the question...
A multimap would be better here with one key and multiple values. Although arguably if the key never changes then you could just store the values in a list. For multiamps you can use Google's guava library or do one yourself. For example (not checked for compilation errors as Im doing this from my head)
Map<String, List<String>> m = new HashMap<>();
if (m.containsKey("key")) {
m.get("key").add("new value");
}
else {
List<String> l = new ArrayList<>();
l.add("new value");
m.put("key", l);
}
You can create a new HashMap, then iterate through the list and put all elements from the map from the list to the main map.
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
for (Map<String, String> mapFromList : list) {
map.putAll(mapFromList);
}
You can try something like this..
ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
HashMap<String, String> comparemap2 = new HashMap<>();
for(HashMap<String, String> i:xmlFileNames){
comparemap2.putAll(i);
}
You may need to consider the case of duplicate keys. else they will get override.
Create a new map and put All each element of arrayList to the map.
But in that case if you have same keys in two element of arrayList (hashmap) then it will override the previous one.

Hashmap value getting updated in all keys

I am having map like this
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map---> {A=[], B=[], C=[]}
I am trying to add "hai" to key A.
But it is getting added to all key. Below is my code
I am wrong somewhere
for (Entry<String, List<String>> entry : map.entrySet()) {
String a = entry.getKey();
if(a.equals(attr)){
List<String> temp = entry.getValue();
temp.add("hai");
map.put(a, temp);
System.out.println("----------"+map);
}
}
output: ------------{A=[hai], B=[hai], C=[hai]}
please suggest
Thanks in advance
Not sure why that's happening, maybe as Eran suggested it's in code you aren't showing. However, there's a much easier way to do this instead of iterating through all the keys...
Map<String, List<String>> map = new HashMap<>();
...
List<String> values = map.get(attr);
if(values == null) {
values = new ArrayList<String>();
map.put(attr, values);
}
values.add("hai");
And I'm just guessing here, but I suspect you are doing this to create the array in the first place...
Map<String, List<String>> map = new HashMap<>();
List<String> values = new ArrayList<>();
map.put("A", values);
map.put("B", values);
map.put("C", values);
This causes A, B, and C to all share the same instance of the List. Therefore when you manipulate the list under one key (say, A), you are really making the same change to the lists stored under all keys, because it is the SAME list for all three.
The fix for that is described above, but essentially you want to create a new instance of List for each key in the map.
You are probably putting the same List in all the values of the Map. However, that happens in code you didn't show. When you put a key in the Map for the first time, make sure you are creating a new List for its value.

Categories

Resources