24

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
user441978
  • 831
  • 9
  • 17
  • 28

9 Answers9

137

You're in object denial. You should use an object that holds the number, name, address, phone (maybe you could call it ContactInformation) and put that into the map.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
49

No. a Map has only one key. If you want your value to contain more information, wrap the strings in a new class:

public class PersonalInfo {
   private final String name;
   private final String address;
   private final String phone;

   // constructor and getters
}

map.put(number, new PersonalInfo(name, address, phone));
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
16

The 'correct' solution is to use an object that holds the values in named fields, but in the spirit of answering the question asked, a simple (if unclean) solution would be to use:

Map<String,List<String>> yourMap = new HashMap<String,List<String>>();

List<String> info = new ArrayList<String>();
info.add(number);
info.add(name);
info.add(address);
info.add(phone);

yourMap.put(key, info);

Note google-collections has a series of classes that implement this structure right out of the box called ListMultimap and it's implementation ArrayListMultimap

Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
  • 3
    I would refrain from providing sample code for a bad solution. I see the reasoning for wanting to explain that, but sample code makes much too likely that it will simply be copied without learning why it's not a good idea. – Joachim Sauer Sep 16 '10 at 12:43
  • 3
    all in the service of giving people enough information to blow their own foot off. 'Yes sir, if you point that at your foot and pull the little thing in front of the handle it will go bang' – Gareth Davis Sep 16 '10 at 12:50
  • 3
    While providing this kind of solution might be "dangerous", there's also some hope that people will see it and realize why it's ugly and problematic, more than just being told so. Well, one can hope at least... – sleske May 17 '11 at 14:27
7

Nope, A Map can have only one key and mapped to one value.

This is the Javadoc for Map:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

What you can do is to create an entity called User with some details e.g

public class User implements Serializable {

    private String firstName;
    private String lastNumber;
    private String address;
    private String phoneNumber;

    //Generated getters and setters here....
}

then add it to a map like so....

Map<String, User> userMap = new HashMap<String, User>();
User user = new User();
//populate user
userMap.put(uniqueUserID, user);
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
5

Just in case you want to maintain a map of: "number, name" --> "address, phone" and you do not wish to create a class to encapsulate these attributes. You may have a look in the handy MultiKey in Apache Commons Collections:

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/keyvalue/MultiKey.html

ThiamTeck
  • 385
  • 1
  • 9
  • https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/keyvalue/MultiKey.html – Tony Feb 26 '15 at 22:13
2

Hmmm, You could create a class for Person with number, name, address and phoneno, then you create a Map

1

Your question suggests you want key on each of the 4 fields and all others become values. While in general, it is one key and multiple values packed on a object.

Please confirm what is required.

Ashish Patil
  • 818
  • 7
  • 15
0

As others have said, a map is a mapping between a key and a value. That is why the javadoc for map says (since generics in v5):

Interface Map<K,V>

... where K is the type of the key, and V is the type of the value. Just <K, V>. You must define exactly two types.

It is worth mentioning that in mathematics 'map' is a term meaning to convert a value of one type into a value of another type. The Java Map is a reflection of this, (as is the method map available on collections in Scala).

Synesso
  • 37,610
  • 35
  • 136
  • 207
  • "It is worth mentioning that in mathematics 'map' is a term meaning to convert a value of one type into a value of another type."Not sure what "type" means in this context, but still I would say: No, "mathematical" maps are not necessarily what you say they are (think of endomorphisms/endofunctions). – Frank Sep 16 '10 at 14:39
  • Specifically, set theory. Where 'type' = a set. And 'map' in the context of a function that maps A -> B. That is a similar effect to what Java's strongly typed Maps provide. – Synesso Sep 16 '10 at 20:23
0

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.

lineage
  • 792
  • 1
  • 8
  • 20