0

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?

1
  • 1
    Maybe save an array of ints inside an Arraylist? Commented Mar 25, 2014 at 22:30

3 Answers 3

5

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>.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

It also is way how to do that, but IMHO create new class with getters and setters is better. Thanks for idea.
0

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

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.