0

I am trying to create a dictionary type record, that holds for example key="Book name" and value= (key="price": $250, key="qty": 10). What would be the easiest way to achieve this is Java ? I have tried by creating a separate class object for they Value.

public class book_info {
int price = 0;
int qty = 0;

public void  book_info(int qty, int price){
    this.qty = qty;
    this.price = price;
    }
}

and creating a HashMap instance;

Map <String, book_info> items = new HashMap<String, book_info>();
items.put("Book1", new book_info(600, 20));
items.put("Book2", new book_info(200, 30));
items.put("Book3", new book_info(100, 50));

This works fine but is there any other alternate way by NOT using a separate class object, instead by just adding multiple key-value pairs in the initialization of HashMap like this;

Map <String, <<String, Integer>,<String, Integer>>> items = new HashMap<String, <<String, Integer>,<String, Integer>>>();
Anum Sheraz
  • 2,383
  • 1
  • 29
  • 54
  • Your best approach is to use OO and model the domain as you started to do. However, I would also add a title to the `BookInfo` object. It also gives you much greater flexibility in the future. – KevinO May 18 '17 at 02:58
  • I think you're looking for `Map>`. But what you have now is much better. – shmosel May 18 '17 at 03:52

1 Answers1

0

your question was probably already been answered, what your trying to do is use an object as the maping key, so instead of having [key, object] you want to have [object1, object2] and each object can be a map of which at the end will make them [[key1, value1][key2, value2]] for more details on using objects as keys see answer:

Using an instance of an object as a key in hashmap, and then access it with exactly new object?

Community
  • 1
  • 1
AbelSurace
  • 2,263
  • 1
  • 12
  • 16