0

Can I have a hash map in Java that looks like this?

HashMap<String, String, Integer> hmap = new HashMap<String, String, Integer>()

My question is similar to this one hereQuestion

I'm a newbie to Java. So what I want to know is, what would be the best data structure to use if I need something like above, if that is not valid?

2
  • 1
    No, but you can have HashMap<Pair<String, String>, Integer> hmap. Commented Sep 12, 2016 at 23:46
  • @rowana you can create a new class holding two String objects and use it as a key. Commented Sep 12, 2016 at 23:47

1 Answer 1

2

Create a simple class holding two String objects:

public class MyKey {
    private String a;
    private String b;

    // ... accessors, mutators etc.
}

And then use it's objects as keys in your map:

HashMap<MyKey, Integer> hmap = new HashMap<>()

Later, to add a new entry:

hmap.put(new MyKey("a", "b"), 2);
Sign up to request clarification or add additional context in comments.

3 Comments

I need to search for one of the strings, if there is a pattern match, extract the other. How could I do that here?
@rowana I think that's not in the scope of your original question, please post a new one. But I'd probably try to iterate through map's entry set, check key part and then extract the other in the same loop.
@Jezor but this time using map structure wont be meaningful. He can just use a list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.