5

Can I have an hashMap with say ID as my key and info, name, quantity as my values?

ok, say I have a class (Products) already that sets my variables, getters and setters. In my Invoice class, which is where the hashMap would be. Would I put like:

private HashMap<String, Products> keys = new HashMap<String, Products>

I'm not quite sure how to access the HashMap though. Say I implement a class that allows me to add and remove invoices from the HashMap, I do not know what the values would be:

keys.put(??value of id??,??not sure what goes here??);
4
  • You can, but you need 2 nested hashmaps
    – Luxspes
    Sep 20, 2010 at 3:49
  • See Javid Jamae's answer for an example of creating an object and adding it to your map.
    – ColinD
    Sep 20, 2010 at 6:01
  • would it look something like this? I'm getting a error on the get methods: Info info = new new(getID(), getName(),getInfo(), getQuantity());
    – Jack
    Sep 20, 2010 at 6:35
  • You'd really need to post more complete code than that, and the exact error you're getting as well, though from what you've said there "new new" definitely isn't going work. Javid Jamae's post is pretty clear and has the exact code you need to create an object and add it to the map.
    – ColinD
    Sep 20, 2010 at 15:35

10 Answers 10

19

Sure. Make another class that contains your info, name and quantity and put that as the value of your HashMap.

6
  • 3
    and you might want to keep the id as well if you need later on? :)
    – setzamora
    Sep 20, 2010 at 3:33
  • Same affect can be achieved with HashMap<Integer, HashMap<String,Object>>, and you do not have to create a new class
    – Luxspes
    Sep 20, 2010 at 3:48
  • 5
    @Luxspes: are you charged for each class you create? Sep 20, 2010 at 4:01
  • 3
    +1 Create a new class, please, for the sanity of the programming world.
    – ColinD
    Sep 20, 2010 at 4:06
  • I am not charged ;-), and I am well aware of the FearOfAddingClasses anti pattern ( c2.com/cgi/wiki?FearOfAddingClasses ). But even then, sometimes (simple problems, querying combinatorial explosion), it is much easier and convenient to create a HashMap instead of a Class.
    – Luxspes
    Sep 20, 2010 at 4:08
7

No, but the best way is to wrap the information you want to keep in the map in a class:

public class Info {
  private String info;
  private String name;
  private int quantity;

  ...

  public Info(String info, String name, int quantity) {
     ...
  }
}

Then do this to put something in the map:

Info info = new Info("info", "name", 2);
Map map = new HashMap<Integer, Info>();
map.put(22, info);

And do this to get something out:

Info info = map.get(22)
13
  • Same affect can be achieved with HashMap<Integer, HashMap<String,Object>>, and you did not have to create a new class
    – Luxspes
    Sep 20, 2010 at 3:36
  • 3
    @Luxspes: No. Unlike a class, a HashMap<String, Object> only tells you "hey guys, there might be some strings associated with some objects! or maybe not!". A class can tell you exactly what fields there ARE, and what their types are too! Creating a new class is not a big deal.
    – ColinD
    Sep 20, 2010 at 4:08
  • @ColinD: Not a big deal, unless you are using it to represent the result of an database query that can be built interactively by the user, then, the flexibility of the Map makes it a perfect solution (and the combinatorial explosion of creating a class for each possible combination the user chooses, makes it unusable)
    – Luxspes
    Sep 20, 2010 at 4:15
  • 2
    I don't think he knows that a class is what he should use here! That's why people answered the question to tell him! I don't think he would have had any reason to ask the question if he knew that. And if he did, then perhaps he wanted to know if there were a better way than using a class. Which there isn't, really. People don't need to know the answer to ask a question. =/
    – ColinD
    Sep 20, 2010 at 5:06
  • 1
    @Luxspes - knowing that a map contain single keys and single values is pretty basic. My assumption when answering the question was that Jack was a beginner, so I suggested a more elegant design. The solution you're providing is obviously for an advanced corner case and seems obviously out of context for this question. If he knew he could have used a class, he could have said "I know I could use a class here, but I'm really interested in knowing..." Sep 20, 2010 at 14:01
1

How about HashMap<Integer, ArrayList<String>> ?

UPDATE: Please try to avoid this, this is a better approach.

7
  • I think you got it backwards, ArrayList<HashMap<String,Object>> would be write, but not HashMap<Integer, ArrayList<String>> (because there would be no way to know which of the elements in the arraylist is your "info", "name" or "quantity"
    – Luxspes
    Sep 20, 2010 at 3:35
  • If you have 4 attributes of 1 ID, why can't you save in that manner?
    – zengr
    Sep 20, 2010 at 3:37
  • because there would be no way to know which of the elements in the arraylist is your "info", "name" or "quantity"
    – Luxspes
    Sep 20, 2010 at 3:39
  • 1
    avoiding assumptions like those can make your code much easier to read and maintain, specially on a big team, on in a very long project, or when you are given the task to maintain the code of someone that no longer works in the company ;-)
    – Luxspes
    Sep 20, 2010 at 3:42
  • 1
    It's essentially using a list as a terrible imitation of an object, one that doesn't (without comments everywhere it's passed to) give you any information on what its fields are supposed to be or even how many fields there are, nor does it allow you to give those fields different (visible) types. Readability will certainly be an issue, yes.
    – ColinD
    Sep 20, 2010 at 4:05
0

Not exactly.

A Map defines a strictly 1 to 1 relationship between keys and values. One key in the map has one value.

If you want to associate multiple values with one key you need to do one of the following:

  • Define a Values class to represent the values as a single object; e.g. as per @Starkey's and @Javed's answers. Then the map becomes a Map<String, Values> (assuming that the key type is String).

  • Define the map as a Map<String,List<Object>> or Map<String,Object[]> and represent the values as an untyped list / array

  • Define the map as a Map<String,Properties> or Map<String,Map<String,Object>> and represent the values as the Java equivalent of an associative array.

Of these, the first option is both the safest (smallest chance of runtime errors), the most efficient and the best style.

(Aside: an Apache commons MultiMap might be considered as another possibility, but the conceptual model and APIs don't really match this use-case.)

0

Sure. Depending on how flexible your datastructe is you can use a Hashmap a la:

  • HashMap<IdType, List<String>>, with IdType String or Integer, depending on the Keys you like to use.
  • HashMap<IdType, String[]>
  • HashMap<IdType, YourObjectType>, with YourObjectType beeing a Object you defined yourself, holding the values you like

YourObjectType can of course be anything you can define as an Object. Also another HashMap if you like.

0

One of the concerns while using a Map would be use of hardcoded keys. If the key is a string, and the key changes. Can consider using a constant instead of a hardcoded string.

Having a dedicated class has the benefit of compiler to check for name changes. However, as mentioned in the earlier comments.. It can become a concern...

In my opinion both are feasible. We need to weigh which option is better depending on the situation

0

Create an object that encapsulates the four together. Something like:

public class Foo {
    private String s1;
    private String s2; 
    private int v3;
    private MyObject obj1
    // constructors, getters, helper functions.
}
0

I think MultiMap from google library could serve the purpose

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html

    Multimap<String, String> map = ArrayListMultimap.create();
    String key = "uniqueKey";
    map.put(key, "value1");
    map.put(key, "value2");
    map.put(key, "value3");

    System.out.println(map);//{uniqueKey=[value1, value2, value3]}
-1

Of course, you could for example declare it like this: HashMap<Integer, HashMap<String,Object>> You use the outer hashmap to link your id with your inner HashMap, and in the inner one, you create keys "info", "name", "quantity" and associate values with them.

Of course, you could also use an ArrayList as the outer collection (it could be a better match for your ID: ArrayList<HashMap<String,Object>> that way you have indexed (id based) access to each of your "info", "name", "quantity" hashmap "records"

2
  • As I've argued elsewhere, this is generally not the best idea.
    – ColinD
    Sep 20, 2010 at 4:34
  • Not the best idea for your requirements? or not the best idea from the requirements of the person who asked the question?. Forgive me, but I believe you are not being objective.
    – Luxspes
    Sep 20, 2010 at 4:48
-1

You could have ID as key and a List or Set (Collection in general) of objects as value.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.