I need to get HashMap which is already inside of HashMap as a value.
HashMap<String, HashMap<String, Product>> myOrders = new HashMap<>();
myOrders = firebaseMethods.getOrders(FirebaseAuth.getInstance().getCurrentUser().getUid(),snapshot);
List<String> Keys = new ArrayList<>(myOrders.keySet());
HashMap<String,Product> Values = myOrders.values();
I've tried already .values() method but it didn't work, any ideas how I can achieve this.
CodePudding user response:
Calling .values() will return a collection of 'values' (in your case, a collection of HashMaps). You can use something like:
List<String> keys = new ArrayList<>(myOrders.keySet());
for(String key: keys) {
HashMap<String, Product> productMap = myOrders.get(key); // This will return the HashMap for the 'key'
... // processing logic goes here
Or better still (as suggested in the comments):
for(Entry<String, Map<String, Product>> entry: map.entrySet()) {
Map<String, Product> productMap = entry.getValue();
// processing logic here ...
CodePudding user response:
You have a HashMap where the key is of type String and the value is of type HashMap<String, Product>.
Example data
Let's create some example code & data to represent that. Let's use the more general Map interface rather than concrete HashMap class.
record Product( int id , String name ) { }
Map < String, Map < String, Product > > myOrders =
Map.of(
"yesterday" ,
Map.of(
"one" , new Product( 1 , "apples" ) ,
"two" , new Product( 2 , "bananas" )
) ,
"today" ,
Map.of(
"one" , new Product( 7 , "oats" ) ,
"two" , new Product( 42 , "quinoa" )
)
);
myOrders.toString():
{today={two=Product[id=42, name=quinoa], one=Product[id=7, name=oats]}, yesterday={two=Product[id=2, name=bananas], one=Product[id=1, name=apples]}}
No need for List with Map#keySet
You use of List & ArrayList is unnecessary, as Map#keySet returns a Set object.
Furthermore, introducing a List here does not make sense, as by definition the order of keys in a Map or HashMap is not defined — the keys may be in any order, even appearing in different order every time you retrieve the keys.
So let's just capture the Set.
Set < String > keySet = myOrders.keySet();
keySet.toString():
[today, yesterday]
Use Collection with Map#valueSet
Reading the Javadoc for Map#values tells you that the method returns a Collection.
So let's capture that Collection object.
Collection < Map < String, Product > > values = myOrders.values();
values.toString():
[{two=Product[id=2, name=bananas], one=Product[id=1, name=apples]}, {two=Product[id=42, name=quinoa], one=Product[id=7, name=oats]}]
