Java: Best way to retrieve values in List - java

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!

Related

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();

How to parse List<Map> in android?

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.

Java create grouped hashtable from objects

I'm writing an application that resends messages received according to the sender, recipient and the keyword used in the sms message. I have a class that fetches from sqlite and returns three objects in an hashmap as follows.
receivedMessages=>map(
0=>map("_ID"=>1,
"sender"=>"*",
"recipient"=>"*",
"keyword"=>"*"
),
1=>map("_ID"=>2,
"sender"=>"8080",
"recipient"=>"*",
"keyword"=>"*"
),
2=>map("_ID"=>3,
"sender"=>"*",
"recipient"=>"22255",
"keyword"=>"*"
)
)
I would love to group them in a map using each of their properties and their corresponding values in an array rather than read them everytime because of efficiency. It's more efficient to fetch from a hashmap 1000 times than reading them from sqlite 1000 times. I want to put them on a hashmap or any other efficient container as shown below.
messages=>map(
"hashmapSenders"=>map(
"*"=>map(1,3),
"8080"=>1,
)
"hashmapRecipients"=>map(
"*"=>map(1,2),
"22255"=>3,
)
"hashmapKeywords"=>map(
"*"=>map(1,2,3)
)
)
so that when I want to get all the senders and the values contained I will call
messages.get("hashmapSenders");
or to get recipients and the values contained I will call
messages.get("hashmapRecipients");
or to get keywords and the values contained I will call
messages.get("hashmapKeywords");
Here is what I have so far
ArrayList<HashMap<String, String>> receivedMessages = getAllMessages();
Iterator<HashMap<String, String>> iterator = receivedMessages.iterator();
HashMap<String, HashMap<String, String>> messages = new HashMap<>();
HashMap<String, String> hashmapSenders = new HashMap<>();
HashMap<String, String> hashmapRecipients = new HashMap<>();
HashMap<String, String> hashmapKeywords = new HashMap<>();
while (iterator.hasNext()) {
HashMap<String, String> map = iterator.next();
hashmapSenders.put(map.get("sender"),map.get("_ID"));
hashmapRecipients.put(map.get("recipient"),map.get("_ID"));
hashmapRecipients.put(map.get("keyword"),map.get("_ID"));
}
messages.put("hashmapSenders", hashmapSenders);
messages.put("hashmapRecipients", hashmapRecipients);
messages.put("hashmapKeywords", hashmapKeywords);
The problem in my code is that the new values will overwrite the older values so I wont get my desired results. Please advice. thank you.
After a search on SO, I found a similar question here
So I modified the answer to fit me. Here is the metnod I used
public void addToMap(HashMap<String, List<String>> map, String key, String value) {
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
So my answer is below
ArrayList<HashMap<String, String>> receivedMessages = getAllMessages();
Iterator<HashMap<String, String>> iterator = receivedMessages.iterator();
HashMap<String, List<String>> messages = new HashMap<>();
while (iterator.hasNext()) {
HashMap<String, String> map = iterator.next();
addToMap(messages, map.get("sender"),map.get("_ID"));
addToMap(messages, map.get("recipient"),map.get("_ID"));
addToMap(messages, map.get("keyword"),map.get("_ID"));
}

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.

Insert an arraylist object in String hashmap

I want to add an Arraylist<String> object(inputArrListObj) into my already existing Map<String, String> (param) which has some input values to be sent.
Map<String,String> param = new HashMap<String, String>();
List<String> obj = inputArrListObj;
param.put("1","Value");
//param.put("2",<Input list values>);
What should be the ideal approach to do the same?
It is not possible with your current declaration.
You must consider changing your map declaration to
Map<String,List<String>> param = new HashMap<String, List<String>>();
That allows you to insert a List as value.
However for the first case (param.put("1","Value");), your List will have only one String in it.
It's look like you want to store in your map abstract named values. If so try to use Map<String, Object> and cast to specific class when you get values from map.
Map<String, Object> param = new HashMap<String, Object>();
List<String> obj = inputArrListObj;
param.put("1", "Value");
param.put("2", obj);
...
List<String> param2 = (List<String>) param.get("2");

Categories

Resources