3

How can I convert this:

Map<String, Integer> itemsBought

So that I can add it on the ArrayList as Follows:

public void add(String prd, int qty){
        orderList.add(new Order(prd, qty));
}

Are there other solutions beside this:

hashMap.keySet().toArray(); 
hashMap.values().toArray(); 

Thank you in advance.

2 Answers 2

11
for (Entry<String, Integer> entry : itemsBought.entrySet()) {
    orderList.add(new Order(entry.getKey(), entry.getValue()));
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (String product : itemsBought.keySet()) {
    int quantity = itemsBought.get(product);
    orderList.add(new Order(product, quantity));
}

I prefer more readability (not much though)

2 Comments

L Regardless of implementation, it is clearly demonstrated by Tarlog's answer that you must iterate the collection in order to populate the ArrayList. That being said, I don't see any value in this answer.
This solution does a map lookup for each key (which might be O(n) worst case, depending on implementation, looking at O(2n)). The first solution, again dependent on the implementation, might simply loop through all entries in O(n) total. For trivial map sizes this is completely irrelevant though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.