How to store more than one string in a Map?

Viewed 25787

Is it possible to set more than two pair value?

For example:

Map<String,String,String,String>

number,name,address,phone - All come together for display the values. Each value associated with others.

9 Answers

No its not. In Java maps are interfaced as Map<K,V> - so only two generic arguments are allowed. The question you ask can now mean two things:

  1. A map where a single key of type K relates to various values of type V. The values themselves may not be mutually related. e.g the key fruits with values apple,banana,guava etc. This is your use case, but only in syntax.
  • One can use Map<K,List<V>> for this.
  • Or better yet Guava's MultiMap, which was purpose built to be capable of storing multiple values for a given key. Note that though similar, it isn't identical to a Map. No List needed.
  1. Since we are allowing multiple values for the same key, the values might as well as have different types. When do multiply typed data for the same key make sense? When they have some relationship to each other, e.g. a key customerId may have values name,number,address etc. potentially of different types. In other, words the data forms the properties of some Object. This is the perfect opportunity to use OOP to create a data structure. This is your use case, in spirit.
  • One can then use Map<K,MyDataStructure> to store these multiple values. Note that the values stay mutable. One needs manual implementation of equals,hashCode though.
 class MyDataStructure{
     Type1 data1;
     Type2 data2;
      ...
 }
  • As of Java 16, a better and recommended way to achieve something similar is by using record. One then uses Map<K,MyRecord>. Note that records are immutable but automatically supply Object related functionality.
record MyRecord(Type1 field1,Type2 field2//,Type3 ...)

In the above discussion, it becomes apparent that we are looking for a data structure each of whose rows or records is identified by a primary key and can contain fields of similar or differing type. Map<K,V> isn't designed for this. A database is.

Related