Kieran
Kieran

Reputation: 656

Referencing the values in one array list to values in another

Is there a data structure in Java where the values in one ArrayList can be used to reference the values in another? For example:

DataStructure<ArrayList<String>, ArrayList<String>> ds = new DataStructure<ArrayList<String>, ArrayList<String>>();

The purpose would be that I could iterate through the data structure later and get both values. For example:

for(int i=0; i<ds.size(); i++) {

     String val1 = ds.get(i).getIndex1().getArrayListValueAt(i);
     String val2 = ds.get(i).getIndex2().getArrayListValueAt(i);

}

I know this looks odd, but it's hard for me to picture.

P.S. Would it be easier to make sure the indexes are the same in both array lists and just loop through one, and as one is grabbed reference the same index in the other. For instance:

int i = 0;
for(String value : values) {
      String val1 = value;
      String val2 = list2.get(i);
      i++;
}

Thanks.

Upvotes: 0

Views: 84

Answers (3)

MatWdo
MatWdo

Reputation: 1740

You can use e.g. Map for your problem, because you can storage all needed collection in one place

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

or e.g.:

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

And then you can e.g. String as key and e.g. List<T> as value

Very important thing is which object do you use as key, because it must have equals/hashCode (if is your object it must be @Override) and next, great when this object is immutable

Upvotes: 1

m_callens
m_callens

Reputation: 6360

I think for your purpose, the Map structure would be better suited. It's a dictionary, so one value is the key and the other is its mapped value.

Map<String, String> ds = new HashMap<>();

Then to loop and access the values, you can use its keySet() method like so...

for (String k : ds.keySet()) {
    String key = k;
    String value = ds.get(k);
}

And to add new key/value pairs to the data structure, you use the put(k, v) method.

ds.put("thisIsAKey", "thisIsTheValue");

Upvotes: 1

Narelle
Narelle

Reputation: 11

Not sure if I understand correctly, it sounds like you wanna have a list which each element in the list would hold pair of values. Would below solution help?

// A class which holds two values...

class MyPair {
    String val1;
    String val2;
}

// And then you list would be ..

List<MyPair> myList = new ArrayList();

// When you looping your list... it would be like something below

for(MyPair mypair : myList) {
     String val1 = mypair.val1;
     String val2 = mypair.val2;
}

Upvotes: 1

Related Questions