0

I want to create an arrayList as following.

id->1512   associated with the values -> 12,45,78
id->1578   associated with the values -> 456,78,87,96

What I have to do? Should I create a 2-d arrayList or can I do that with single dimension arraylist?

1
  • 1
    You need a MultiMap<Integer, Integer> (e.g. from Guava), or a Map<Integer, Set<Integer>> Commented Feb 24, 2013 at 10:05

3 Answers 3

5

You are looking for something like this:

Map<Integer, List<Integer>>
Sign up to request clarification or add additional context in comments.

5 Comments

I prefer not using third party libraries
@Aubin: Why not? A MultiMap will result in much nicer code, as you don't have to null check every key.
@jlordo thanks, but never really used Guava library before .. :P. but sounds like a good one :)
@PremGenError: Compare the code in my answer to what would be needed to add the key/value pairs to your Map<Integer, List<Integer>>
2

Use the Guava Library, and you can do this for your associations:

Multimap<Integer, Integer> map = HashMultimap.create();
map.putAll(1512, Arrays.asList(12, 45, 78));
map.putAll(1578, Arrays.asList(456, 78, 87, 96));

Here's an example how you can get the values:

int key = 1512;
for (Integer value : map.get(key)) {
    System.out.println("Associated " + key + " -> " + value);
}

Here's a link to Guava's JavaDoc

3 Comments

@Aubin: Sorry, I can't understand what your comment means in regard to my answer.
Occam's razor says you have to adapt means to goals. Guava is over sized for this simple problem. Dependencies reduces the re-usability of a solution.
@Aubin: Ok, makes sense now. In this case, we have to agree to disagree, because Guava makes programming this kind of map so much easier. You don't have to null check when inserting, you don't have to think about what kind of collection is used to save the values and so forth.
0

You dont need ArrayList. read abut Map

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.