简体   繁体   中英

Any data structure in java that supports multiple keys - not map exactly

I came a cross a situation where I need something like:

197 => 6   (1 year)
197 => 12  (2 years)

Want to add multiple products and their price, based on the years of subscription, the value varies.

I wonder if we have any data structure in java that supports duplicates keys (should behave like map but must support duplicate keys).

I can do by creating a class but just wanted to know if there is anything that supports this thing..It is more like a MAP but no the map since it needs to support multiple keys.

Yes you can do it using existing libraries like guava. Here is a link to the interface MultiMap of guava library link . Here an example on how to use it (taken from here ):

  Multimap<String, String> myMultimap = ArrayListMultimap.create();

  // Adding some key/value
  myMultimap.put("Fruits", "Banana");
  myMultimap.put("Fruits", "Apple");
  myMultimap.put("Fruits", "Pear");
  myMultimap.put("Vegetables", "Carrot");

  // Getting the size
  int size = myMultimap.size();
  System.out.println(size);  // 4

  // Getting values
  Collection<string> fruits = myMultimap.get("Fruits");
  System.out.println(fruits); // [Bannana, Apple, Pear]

  Collection<string> vegetables = myMultimap.get("Vegetables");
  System.out.println(vegetables); // [Carrot]

The second possibility is to create a Map<String, List<Object>> and manually handling the reference to the list of objects that you need to associate to a single key.

There is MultiMap but this doesn't look like a good use case, You should use a Map<Product, Map<Years, Price>>

ie

197 => {
    1 year => 6
    2 years => 12
}

If you don't want to use an external library like guava, you could create your own.

HashMap<Integer, ArrayList<String>> hm = new HashMap();
for(int i = 0; i < 10; ++i){
 ArrayList<String> li = new ArrayList();
 for(int j = 0; j < 10; ++j)
    li.add(j * i);
 hm.put(i, li);
}
System.out.println(hm.get(4));//[0,4,8,12....]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM