Retriving the values of Map inside List - java

ArrayList<HashMap<String, Object>> list = ArrayList<HashMap<String, Object>>()
I have an array list which contains an hashmap, i am able to get the position of my List , now how would i get the key and value of the object in my List.
#Override
public View getDropDownView() {
System.out.println(data.get(position)); // i am getting my List Objects
}
// The below is the output of data.get(position)
{"title":"hello"}, => 0
{"title":"hello1"}, => 1
{"title":"hello2"}, => 2
{"title":"hello3"}, => 3

Try this out :
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
for (Map element : list) {
Set<Map.Entry<String, Object>> entrySet = element.entrySet();
for (Map.Entry<String, Object> mapEntry : entrySet) {
System.out.println("Key is : " + mapEntry.getKey());
System.out.println("Value is : " + mapEntry.getValue());
}
}

Little modification in above code.Please find the below code snippets.
public class Test01 {
public static void main(String[] args) {
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map=new HashMap<String, Object>();
map.put("test_key", "test_value");
data.add(map);
HashMap hashMap = data.get(0);
Iterator<Object> iterator=hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> entry=(Entry<String, Object>) iterator.next();
System.out.println("Key :"+entry.getKey()+" Value : "+entry.getValue());
}
}
}
i hope this may be help...

With full example try this:
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> map1 = new HashMap<String, Object>();
HashMap<String, Object> map2 = new HashMap<String, Object>();
map1.put("title", "hello");
map2.put("title2", "hello2");
list.add(map2);
list.add(map1);
HashMap<String, Object> innerMap;
for(int i=0;i<list.size();i++)
{
innerMap = list.get(i);
for (Map.Entry<String, Object> entry : innerMap.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}

Your question leaves much to be desired, but I believe this is what you're looking for
public class HashMapClass {
public static void main(String[] args){
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
//Get the Hasmap at position
HashMap map = data.get(position);
//Get the data in a the hashmap
Object obj = map.get(key);
}
}

You could use Map.Entry
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Y {
public static void main(String[] args) {
// Your data structure...
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//Add some dummy data
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
//Add the Map to the List
list.add(map);
int positionInList = 0; //Manipulate this how you want
//Use Map.Entry to access both key and value
for (Entry<String, Object> entry : list.get(positionInList).entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
}
}

Related

How to filter map of map using java stream

How can I filter map of map using java stream. I can do it using double loop but I think this is not efficient.
public class MapUsage {
static Map<Integer, Map<Integer, String>> parentMap = new HashMap<>();
static Map<String, String> userRole = new HashMap<>();
public static void main(String ... args){
initializeData();
displayMapForUser("user1", parentMap);
// printMap(parentMap);
}
private static void displayMapForUser(String user1, Map<Integer, Map<Integer, String>> parentMap) {
Integer role = new Integer(userRole.get(user1));
Map<Integer, Map<Integer, String>> userMap = new HashMap<>();
Map<Integer, String> childMap = new HashMap<>();
for(Map.Entry<Integer, Map<Integer, String >> entry : parentMap.entrySet()){
for(Map.Entry<Integer, String > entry1: entry.getValue().entrySet()){
if(entry1.getKey().equals(role))
childMap.put(entry1.getKey(), entry1.getValue());
}
userMap.put(entry.getKey(), childMap);
}
printMap(userMap);
}
private static void printMap(Map<Integer, Map<Integer, String>> parentMap) {
for(Map.Entry<Integer, Map<Integer,String> > entry: parentMap.entrySet()){
System.out.println("key: "+entry.getKey());
System.out.println("value: "+entry.getValue());
}
}
private static void initializeData() {
Map<Integer, String > childMap1 = new HashMap<>();
Map<Integer, String > childMap2 = new HashMap<>();
userRole.put("user1", "1");
userRole.put("user2", "2");
userRole.put("user3", "3");
userRole.put("user4", "4");
childMap1.put(1, "one");
childMap1.put(2, "two");
childMap1.put(3, "three");
childMap1.put(4, "four");
parentMap.put(1, childMap1);
childMap2.put(1, "one");
childMap2.put(2, "two");
childMap2.put(3, "three");
parentMap.put(2, childMap2);
}
}
Output is:
key: 1
value: {1=one}
key: 2
value: {1=one}
You could use Collectors.toMap there as:
Map<Integer, Map<Integer, String>> userMap = parentMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()
.entrySet().stream()
.filter(en -> en.getKey().equals(role))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
But note, there is no significant performance efficiency that you gain here. Just readability and you could have possibly written that as :
Map<Integer, Map<Integer, String>> usersMap = new HashMap<>(parentMap);
usersMap.values().forEach(innerMap -> innerMap.entrySet().removeIf(en -> !en.getKey().equals(role)));

java merging two List<Map<String, Object>> to HashMap<String, Object>

I have two list called List<Map<String, Object>> cpuReport and List<Map<String, Object>> memoryReport, I want to put these two list into one HashMap where cpureport and memoryReport can have same or different keys in HashMap.
memoryReport : [{robot=GEMPSAPPPROD02, memory_min=3.17, memory_max=90.79, memory_avg=31.857100643332412, memory_50=34006, memory_60=5700, memory_65=2480, memory_100=2450}, {robot=MUMGEMIDADBPROD05, memory_min=6.07, memory_max=8.75, memory_avg=8.184755153233644, memory_50=44635, memory_60=0, memory_65=0, memory_100=0}]
cpuReport : [{robot=Hema, cpu_min=1.12, cpu_max=1.12, cpu_avg=1.12, cpu_50=0, cpu_60=0, cpu_65=0, cpu_100=0}, GEMPSAPPPROD02={robot=GEMPSAPPPROD02, cpu_min=0.03, cpu_max=35.88, cpu_avg=2.6957142857143097, cpu_50=44636, cpu_60=0, cpu_65=0, cpu_100=0}]
mergedMap: GEMPSAPPPROD02={robot=GEMPSAPPPROD02, memory_min=3.17, memory_max=90.79, memory_avg=31.857100643332412, memory_50=34006, memory_60=5700, memory_65=2480, memory_100=2450,cpu_min=0.03, cpu_max=35.88, cpu_avg=2.6957142857143097, cpu_50=44636, cpu_60=0, cpu_65=0, cpu_100=0},MUMGEMIDADBPROD05={robot=MUMGEMIDADBPROD05, memory_min=6.07, memory_max=8.75, memory_avg=8.184755153233644, memory_50=44635, memory_60=0, memory_65=0, memory_100=0},Hema={robot=Hema, cpu_min=1.12, cpu_max=1.12, cpu_avg=1.12, cpu_50=0, cpu_60=0, cpu_65=0, cpu_100=0}
public List<Map<String, Object>> getMergedReport(List<Map<String, Object>> cpuReport,
List<Map<String, Object>> memoryReport) {
Map<String, Object> MergedMap = new HashMap<String, Object>();
List<Map<String, Object>> listOfBothMaps = new ArrayList<>();
String robotFromcpu = null;
try {
for (Map<String, Object> cpuMap : cpuReport) {
robotFromcpu = (String) cpuMap.get("robot");
MergedMap.put(robotFromcpu, cpuMap);
}
for (Map<String, Object> memoryMap : memoryReport) {
String robotFromMemory = (String) memoryMap.get("robot");
Map<String, Object> map = (Map<String, Object>) MergedMap.get(robotFromMemory);
if(map != null){
map.putAll(memoryMap);
}
else{
MergedMap.put(robotFromMemory, memoryMap);
}
LOGGER.info("The merged map is : " + map);
listOfBothMaps.add(map);
}
} catch (Exception e) {
LOGGER.info("The exception is : " + e.getMessage());
}
return listOfBothMaps;
}
Working code:
Map<String, Object> mergedMap = new HashMap<String, Object>();
List<Map<String, Object>> listOfMergedMaps = new ArrayList<>();
String robotFromcpu = null;
for (Map<String, Object> cpuMap : cpuReport) {
robotFromcpu = (String) cpuMap.get("robot");
mergedMap.put(robotFromcpu, cpuMap);
}
for (Map<String, Object> memoryMap : memoryReport) {
String robotFromMemory = (String) memoryMap.get("robot");
Map<String, Object> map = (Map<String, Object>) mergedMap.get(robotFromMemory);
if(map != null){
map.putAll(memoryMap);
LOGGER.info("The merged map is : " + map);
}else{
mergedMap.put(robotFromMemory, memoryMap);
}
}
for(Map.Entry<String, Object> map : mergedMap.entrySet()) {
listOfMergedMaps.add((Map<String, Object>)map.getValue());
}
below should work :
public List<Map<String, Object>> getMergedReport(List<Map<String, Object>> cpuReport,
List<Map<String, Object>> memoryReport) {
Map<String, Object> MergedMap = new HashMap<String, Object>();
List<Map<String, Object>> listOfBothMaps = new ArrayList<>();
cpuReport.addAll(memoryReport); // merge two lists
Iterator itr_mergedList= cpuReport.iterator(); // get iterator for list
while(itr_mergedList.hasNext())
{
HashMap m= (HashMap)itr_mergedList.next();
Set s = m.entrySet(); // get no. of entries in above list
Iterator itr_entrySet= s.iterator(); // get iterator for above entry set
while(itr_entrySet.hasNext())
{
Map.Entry en=(Map.Entry) itr_entrySet.next();
MergedMap.put((String)en.getKey(), en.getValue()); // put in merged map
}
}
listOfBothMaps.add(MergedMap); // add map obj to list
return listOfBothMaps;
}

Using multiple HashMaps to retrieve values in Java

Consider two HashMaps. The first one contains the product name and product category code as key and value respectively. The second HashMap contains the product name and the units sold. I need to write a Java function which accepts the two hash maps and return the names of products in each category which is having the highest number of units sold.
Input1 :{“lux”:”soap”,”colgate”:”paste”, ”pears”:”soap”,”sony”:”electronics”,”samsung”:”electronics”}
Input 2:{“lux”:1000,”colgate”:500,”pears”:2000,”sony”:100,” samsung”,600}
Output: {“pears”,”colgate”,”samsung”}
#Arjun: answer code is given below :
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MultipleHashMapAccessDemo {
protected Map<String, String> getProductCategoryMap() {
Map<String, String> productCategoryMap = new HashMap<String, String>();
productCategoryMap.put("Lux", "Soap");
productCategoryMap.put("Pears", "Soap");
productCategoryMap.put("Dove", "Soap");
productCategoryMap.put("Colgate", "Paste");
productCategoryMap.put("Babul", "Paste");
productCategoryMap.put("Vico", "Paste");
return productCategoryMap;
}
protected Map<String, Integer> getProductUnitsSoldMap() {
Map<String, Integer> productUnitsSoldMap = new HashMap<String, Integer>();
productUnitsSoldMap.put("Lux", 1000);
productUnitsSoldMap.put("Pears", 3000);
productUnitsSoldMap.put("Dove", 3010);
productUnitsSoldMap.put("Colgate", 50);
productUnitsSoldMap.put("Babul", 45);
productUnitsSoldMap.put("Vico", 80);
return productUnitsSoldMap;
}
protected Map<String, String> getExpectedProductCategoryMap(
Map<String, String> productCategoryMap,
Map<String, Integer> productUnitsSoldMap) {
Map<String, String> expectedProductCategoryMap = new HashMap<String, String>();
Set<String> categortSet = new HashSet<String>();
Iterator iterator = productCategoryMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> mEntry = (Map.Entry) iterator.next();
categortSet.add(mEntry.getValue());
}
for (String category : categortSet) {
int tempUnits = 0;
String desiredProductName = null;
for (Object object : productUnitsSoldMap.entrySet()) {
Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) object;
String product = entry.getKey();
if (category.equals(productCategoryMap.get(product))) {
if (tempUnits < entry.getValue()) {
tempUnits = entry.getValue();
desiredProductName = product;
}
}
}
expectedProductCategoryMap.put(category, desiredProductName);
}
return expectedProductCategoryMap;
}
public static void main(String... strings) {
MultipleHashMapAccessDemo accessDemo = new MultipleHashMapAccessDemo();
Map<String, String> productCategoryMap = accessDemo
.getProductCategoryMap();
Map<String, Integer> productUnitsSoldMap = accessDemo
.getProductUnitsSoldMap();
Map<String, String> expectedProductCategoryMap = accessDemo
.getExpectedProductCategoryMap(productCategoryMap,
productUnitsSoldMap);
for (Object object : expectedProductCategoryMap.entrySet()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) object;
System.out.print("Category name is : " + entry.getValue());
System.out.println(" And Product name is : " + entry.getKey());
}
}
}
Basically, I'll hold a map with from the category to the most popular item and its counter. You can either do this with two separate Maps, jimmy up a quick and dirty class to hold the info, or use something like Apache Commons Lang's Pair class. Without relying on any third party, I'd just define a simple class like this:
public class Item {
String name;
int amount;
// constructor from name, amount
// getters and setters
}
Now, you can iterate over the sales map and just save the most popular item for each category:
public Set<String> getPopularItems
(Map<String, String> itemCategories,
Map<String, Integer> itemSales) {
Map<String, Item> result = new HashMap<String, Item();
for (Map.Entry<String, Integer> salesEntry: itemSales) {
String itemName = itemSales.getKey();
int itemAmount = itemSales.getValue();
String category = itemCategories.get(itemName);
if (result.contiansKey(category)) {
int currAmount = result.get(category).getAmount();
if (itemAmount > currAmount) {
result.put (category, new Item (itemName, itemAmount));
}
} else {
result.put (category, new Item (itemName, itemAmount));
}
}
return result.keySet();
}
Note that this is a simplified implementation that does not deal with malformed inputs (e.g., a category that appears in one map but not the other), or with edge cases (e.g., two items with the same amount of sales). This is done for clarity's sake - I'm sure you could add these on later if needed.

How to get the data from nested Hashmap?

This line of code returns List<HashMap<String, String>>
List<HashMap<String,String>> map= restTemplate.postForObject(url,mvm,List.class);
And through this code, I can succesfully get the value of id and name in index[0].
List<HashMap<String, String>> map;
map.get(0).get("id");
map.get(0).get("name");
The Structure of the map
HashMap<"id","1">
<"name","john">
<"parameters",HashMap<"key", "val"> <"key2","val2">>
How can I get data from parameters? thanks.
To get the value of parameter you could do
String val = ((HashMap)map.get(0).get("parameters")).get("key");
although you will need to change
HashMap<String, String> to HashMap<String, Object> for this to work
((HashMap)map.get(0).get("parameters")).get(map_key)
Try below code:
for(int i=0;i<map.size();i++){
map.get(i).get("id");
map.get(i).get("name");
}
Save each value to your needed variables.
You can only get string values from the Map since it's declared List<HashMap<String,String>>. If it would say List<HashMap<String, Object> you could do something like this:
package com.stackoverflow.maps;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class InnerMaps {
public InnerMaps(List<HashMap<String,Object>> outerList) {
System.out.println("InnerMaps.<init>");
for (HashMap<String, Object> outerMap: outerList) {
for (String key: outerMap.keySet()) {
Object value = outerMap.get(key);
if (value.getClass().getName().equals(HashMap.class.getName())) {
HashMap<String,String> hashMap = (HashMap<String,String>)value;
System.out.println(key + ", hashMap:" + hashMap );
} else {
System.out.println(key + " : " + value);
}
}
}
}
public static void main(String[] args) {
List<HashMap<String,Object>> theList = new ArrayList<>();
HashMap<String,String> innerHashmap = new HashMap<>();
innerHashmap.put("innerOne", "innerOneValue");
innerHashmap.put("innerTwo", "innerTwoValue");
HashMap<String, Object> outer = new HashMap<>();
outer.put("one", new String("One Value"));
outer.put("two", innerHashmap);
theList.add(outer);
InnerMaps app = new InnerMaps(theList);
}
}

Sorting HashMap

I have an ArrayList of HashMap. Each HashMap contains many key-value-pairs. I want to sort the ArrayList by the value of the key distance in the HashMap.
ArrayList<HashMap<String, String>> arrayListHashMap =
new ArrayList<HashMap<String, String>>();
{
HashMap hashMap = new HashMap<String, Object>();
hashMap.put("key", "A key");
hashMap.put("value", "B value");
hashMap.put("distance", 2536);
arrayListHashMap.add(hashMap);
}
{
HashMap hashMap = new HashMap<String, String>();
hashMap.put("key", "B key");
hashMap.put("value", "A value");
hashMap.put("distance", 2539);
arrayListHashMap.add(hashMap);
}
Add all the HashMaps to a list and sort it using a custom Comparator like this:
Collections.sort(arrayListHashMap, new Comparator<HashMap<String, Object>>() {
#Override
public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
return ((Integer) o1.get("distance")).compareTo(
(Integer) o2.get("distance"));
}
});
Full example:
public static void main(String... args) {
List<HashMap<String, Object>> arrayListHashMap =
new ArrayList<HashMap<String, Object>>();
{
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("key", "A key");
hashMap.put("value", "B value");
hashMap.put("distance", 2536);
arrayListHashMap.add(hashMap);
}
{
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("key", "B key");
hashMap.put("value", "A value");
hashMap.put("distance", 2539);
arrayListHashMap.add(hashMap);
}
Collections.sort(arrayListHashMap,
new Comparator<HashMap<String, Object>>() {
#Override
public int compare(
HashMap<String, Object> o1,
HashMap<String, Object> o2) {
return ((Integer) o1.get("distance")).compareTo(
(Integer) o2.get("distance"));
}
});
System.out.println(arrayListHashMap);
}
You can try to sort with a custom comparator:
Collections.sort(arrayListHashMap, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> m1, HashMap<String, String> m2) {
return Integer.valueOf(m1.get("distance")).compareTo(Integer.valueOf(m2.get("distance")));
}
});
Note that I assumed all your values are strings which is not the case in your example (distance is an int value).

Categories