android arraylist get hashmap position - java

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

Related

Populate Map<String, Map<String, Integer>> with values

I need to fill Map<String, Map<String, Integer>> with values. My code is as follows:
// tags, <types, prices>
Map<String, Map<String, String>> outter = new HashMap<>();
List<String> tags = new ArrayList<String>();
tags.add("1tag");
tags.add("2tag");
List<String> types = new ArrayList<String>();
types.add("paper");
types.add("metal");
List<String> prices = new ArrayList<String>();
prices.add("1.20");
prices.add("2.20");
for (int t = 0; t < tags.size(); t++) {
Map<String, String> inner = new HashMap<>();
for (int tp = 0; tp < types.size(); tp++) {
for (int p = 0; p < prices.size(); p++) {
inner.put(types.get(tp), prices.get(p));
}
}
outter.put(tags.get(t), inner);
}
System.out.println("filled outter:" + outter);
The result is:
filled outter:{2tag={paper=2.20, metal=2.20}, 1tag={paper=2.20, metal=2.20}}
The correct result I want is:
filled outter:{2tag={paper=1.20, paper=2.20, metal=1.20, metal=2.20}, 1tag={paper=1.20, paper=2.20, metal=1.20, metal=2.20}}
How to prevent overriding values and get correct result?
Help..
As reported by others Java's Map interface maps each key to a single value. If you want to assign multiple values to a single key, you can either do that manually (mapping to a List). Or use a library that already has that, like Guava's Multimap for your inner map.
That way you will have something like:
filled outter:{2tag={paper=[1.20, 2.20], metal=[1.20, 2.20]}, 1tag={paper=[1.20, 2.20], metal=[1.20, 2.20]}}
And you would define your map as:
Map<String, Multimap<String, String>> outter = new HashMap<>();
You have an example usage of Multimap here.
Because you can't set two keys inside a Map with the same name. You should create a ArrayList or something simular inside the outer Map.

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.

Put value LinkedHashMap multidimensional

I have the following structure:
import java.util.LinkedHashMap;
...
LinkedHashMap <String, Object>level0 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level1 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level2 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level3 = new LinkedHashMap<String, Object>();
level1.put("level2", level2);
level2.put("level2", level3);
level0.put("level1", level1);
System.out.println(level0);
Output this:
{
level1={
level2={}
}
}
I need to set a value through a "path" (or something), would be something like this:
MapThisObject example = new MapThisObject(level0);
example.putValue("level1.level2", "string", "test");
example.putValue("level1.level2", "int", 1);
example.putValue("level1.level2", "object", new LinkedHashMap());
System.out.println(example.result());
/*output:
{
level1={
level2={
string="test",
int=1,
Object={}
}
}
}
*/
In other words, there is the possibility to put or set values ​​for "multidimensional objects" through a "path" (like Xpath)?
A simple example
public static void set(Map<String, Object> map, String path, Object value) {
String[] parts = path.split("\\.");
for(int i = 0; i < parts.length-1 ; i++) {
String key = parts[i];
Map<String, Object> map2 = (Map<String, Object>) map.get(key);
if (map2 == null) {
map.put(key, map2 = new LinkedHashMap<String, Object>());
}
map = map2;
}
map.put(parts[parts.length - 1], value);
}
set(example, "level1.level2.string", "test");
set(example, "level1.level2.int", 1);
From what you've described, it sounds like all you need is a map containing maps, nested to however many axes you're trying to select from.
The alternative would be to build your own tree structure, of course. Or to express it as an XML DOM tree, which would let you use standard XPath.

Retrieve all values from HashMap keys in an ArrayList Java

Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.
Map.put(DATE, value1);
Map.put(VALUE, value2);
arraylist.put(Map);
Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist? i have tried this
if(!list.isEmpty()){ // list is an ArrayList
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
}
Log.d(TAG, "map size is" + map.size());
String [] keys = new String[map.size()];
String [] date_value = new String[map.size()];
String [] value_values = new String[map.size()];
int i = 0;
Set entries = map.entrySet();
Iterator iterator = entries.iterator();
while(iterator.hasNext()){
Map.Entry mapping = (Map.Entry)iterator.next();
keys[i] = mapping.getKey().toString();
date_value[i] = map.get(keys[i]);
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
i++;
}
But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks
Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key: map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
Also, your 1st for-loop looks odd to me: -
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.
EDIT: -
You can also use entrySet if you want both key and value for your map. That would be better bet for you: -
Map<String, Integer> map = new HashMap<String, Integer>();
for(Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
Try it this way...
I am considering the HashMap with key and value of type String, HashMap<String,String>
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("key1","Val1");
hmap.put("key2","Val2");
ArrayList<String> arList = new ArrayList<String>();
for(Map.Entry<String,String> map : hmap.entrySet()){
arList.add(map.getValue());
}
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());
Put i++ somewhere at the end of your loop.
In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.
FYI: the below is doing a redundant search:
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
replace with
if(keys[i].equals(DATE)){
date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){
value_values[i] = mapping.getValue()
}
Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.
This is incredibly old, but I stumbled across it trying to find an answer to a different question.
my question is how do you get the values from both map keys in the arraylist?
for (String key : map.keyset()) {
list.add(key + "|" + map.get(key));
}
the Map size always return a value of 2, which is just the elements
I think you may be confused by the functionality of HashMap. HashMap only allows 1 to 1 relationships in the map.
For example if you have:
String TAG_FOO = "FOO";
String TAG_BAR = "BAR";
and attempt to do something like this:
ArrayList<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> map = new HashMap<>();
for (String bar : bars) {
map.put(TAG_BAR, bar);
}
This code will end up setting the key entry "BAR" to be associated with the final item in the list bars.
In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.
Suppose I have Hashmap with key datatype as KeyDataType
and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Java 8 solution for produce string like "key1: value1,key2: value2"
private static String hashMapToString(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.joining(","));
}
and produce a list simple collect as list
private static List<String> hashMapToList(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.toList());
}
It has method to find all values from map:
Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
Iterate over vs to do some operation

Categories

Resources