Reputation: 15
I have two lists that each contain 2500 values.
List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();
I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:
for (int i = 0; i < headers.size(); i++) {
for (int in = 0; in < data.size(); in++) {
}
}
It's critical the index of each list match each other when combining these two lists. So headers.get(9);
must match data.get(9);
.
I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0);
would be paired with data.get(0);
.
Any help would be appreciated.
Upvotes: 1
Views: 374
Reputation: 3832
Make a new class:
class HeadersWithData{
String header;
String data;
HeadersWithData(String header, String data){
this.header = header;
this.data = data;
}
}
Declare your list:
List<HeadersWithData> combinedList = new ArrayList<>();
And fill the list:
for (int i = 0; i < headers.size(); i++){
combinedList.add(new HeadersWithData(headers.get(i), data.get(i)));
}
Note: This is a one-dimensional list. A two-dimensional list would not make any sense in your case.
Upvotes: 1
Reputation: 3609
I'm not really sure if the loop you presented is what what you really wanted to archieve, but if you wanted every element of the first list correspond to exactly one element of the second list I would suggest using Map<String, String>
. This allows you to map every element of the first list of strings to one elements of the second list. Each pair is then stored as an Map.Entry<Key,Value>
.
That way you are able to iterate only once through the map using for example loop like this:
for(Map.Entry<String,String> entry : map.entrySet()) {...}
Upvotes: 0
Reputation: 14572
About
It's critical the index of each list match each other when combining these two lists.
Create a simple class to hold both value
class MyData{
String header;
String data;
}
Then use a single List<MyData>
. You will only have one List
of 2500 items.
Based on what you do with those data, other collection could be more efficient to read, but not to update.
Upvotes: 2
Reputation: 198033
If you need the one list to contain the same pairs that you'd get doing the nested loop, there's nothing you can do. You're iterating over 2500*2500=6250000 pairs. Nothing will make that fast. Iterating over one list instead of the nested for loops will not make a difference.
If you don't want to iterate over every combination of elements from both lists, but iterate over one list once and then iterate over the other list once, then that's equivalent to doing one for loop after the other, not one for loop inside of the other. And that will be fast whether you combine them into one big list, or iterate over one list and then the other.
Upvotes: 1