A Key That Gives Multiple Results

I'm new to programming, so I'm sorry if this is a stupid question. I was wondering if there is a data type that returns (possibly) more than one response per key. For example:

TestType<int,String> test = new TestType<int,String>();

So, if you type, test.getKey (1), you can get {"hello", "this", "is", "a", "test"}.

Basically, is there a data type that can return multiple responses, sort of like HashMap and List together?

+3


source to share


5 answers


Not in standard Java. However, you can use the Guava MultiMap collection type . There are other libraries that provide a collection with multiple cards as well.

If for some reason you don't want to use a third party library, you can also flip your own data structure. However, this definitely reinvents the wheel and is a bit of a pain. You must define test

how Map<Integer, Set<String>>

and then write accessor methods to initialize the empty key input under appropriate conditions.



Note that Java does not allow primitive types (like the int

way you are using) to be used as generic values ​​for type parameters. You must use Integer

. Due to autoboxing, you can still use test.get(1)

to get the values ​​stored under the key 1

.

+5


source


You might want to use the MultiMap from apache collection collection and its concrete implementation MultiHashMap



You can also use Map<Integer,List<String>>

- as you suggested.

+2


source


What you are requesting is called multimap, there are several implementations in Guava and another in Apache commons collections .

+1


source


Java does not offer multimap

as it is not used often (their assertion). But SUN offers a small example of how to create a multi-frame yourself using a Map

and a List

like this:

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

      

You can see an example here at Collections / Java Maps . Check a paragraph on multimars like code

0


source


Amit is on the right track. You can also create a class for the answer. This can help you increase your encapsulation.

Map<Integer, MyAnswer>

      

where MyAnswer can include attributes for the data you want to manage. Implementing your own class gives you a world of possibilities.

0


source







All Articles