Reputation: 652
I need to save two values to one cell of ArrayList. Immediatelly, I'am going through the List and sum values up. What is the best to use for storing data to Arraylist? Map? I tried something like this:
List<Map<Integer, Integer>>
But I sometimes I need to get KEY and sometimes VALUE and it's quite difficult to get them. Is there simplier way?
Upvotes: 0
Views: 1119
Reputation: 1455
If you need multiple values for specific keys,
Map<Integer, List<Integer>>
check (Guava's Multimap). You could find there quite nice classes or utility classes for transformation.
If this is not suitable for you, you definitions is not that bad, but if there is single key=value pair, this could be nicer:
List<Map.Entry<Integer, Integer>>
Entry is simple inner class inside map, which stores Key/Value pairs. Also, if you stick with your approach (could be complicate) or you switch to Entry, it is not that difficult to change (in case you need always Keys or always only Values.
List<Entry<Integer, Integer>> values; // filled, initialised
// Getting only Keys
values.stream().map(Entry::getKey); // Java8 stuff - method reference
// Getting only Values
values.stream().map(Entry::getValue); // Java8 stuff - method reference
Here read about method reference
Upvotes: 0
Reputation: 16383
Are you just trying to store a tuple (i.e. two values) in each slot of an array list?
Simplest way to do this is to either have a Tuple class (getFirst(), getSecond()) - or if you want it to be quick and dirty, store an array of size 2:
List<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1, 2});
If that's not what you are trying to do, provide some clarification.
Upvotes: 1
Reputation: 198033
If you need to store two values as a unit, then write a class containing two int
fields, named appropriately. For example, if your two int
values represent x and y coordinates, write a class
class Point {
private int x;
private int y;
...
}
...and then use an ArrayList<Point>
.
Upvotes: 5