Reputation: 1149
I am kind of lost on which data structure to use to solve my problem effectively. I want to map an array to a value. What I mean is that if I have 1000 values, I need to be able to map multiple other values to each of the 1000 values.
For example,
I have 1000 A values from 1-1000. For each value A, I want to map k other values B (these range from 1-1000 also). But I do want to ensure that whatever values are mapped to A are not duplicates. Mapped values between different A values can be the same (i.e. both 2 and 1000 have 67 mapped to them).
1 -> 138, 92, 835, 841, 12
2 -> 766, 324, 26, 933, 62
3 -> 53, 131, 62, 121, 67
4->160, 160 #NOT OK
4-> 162, 171, 594, 912, 455
...
1000->146, 981, 67, 246, 146
So when I look at some arbitrary value A, I should be easily able to identify whatever values are mapped to it. So if I wanted to access value 3, I should be able to print out both the value A (3) and its associated values (53, 131, 62, 121, 67).
I hope that makes sense. What would be the best way of achieving this kind of data structure? Any help of an explanation or an example would be much appreciated.
Upvotes: 0
Views: 125
Reputation: 17630
You want an array list of sets:
ArrayList<Set<Long>>
Set requires that the value is in the collection once and only once, and of course the list is a list of these collections.
You can then use the get(index)
method on ArrayList to get specific ordinals.
ArrayList<Set<Number>> mappings = new ArrayList<Set<Long>>();
Set<Long> s = new HashSet<Long>();
long[] n = {138, 92, 835, 841, 12};
s.addAll( Arrays.toList( n));
mappings.add(1, s);
// etc.
Later, to fetch:
Set<Long> result = mappings.get(1); // for element in slot 1...
Upvotes: 1
Reputation: 424993
if you have continuous values (or even near-continuous), you don't need to "map" then - you can use a simple array of array:
int[][] a = new int[1001][];
then for each value, create an array of int:
a[1] = new int[]{138, 92, 835, 841, 12};
etc
Upvotes: 0
Reputation: 240880
Use
Map<Long, Set<Long>> numberToValuesMap;
Set
for uniqueness
Upvotes: 2