Reputation: 153
I currently have an ArrayList
called months.
ArrayList<MonthData> months;
MonthData
is a class that is basically a model for data.
public class MonthData {
int y;
int m;
float h;
...
public MonthData(String data) throws Exception {
...
this.parseData(data);
}
void parseData(String csvData) {
String[] parseResult = csvData.trim().split("\\s+");
this.setYear(parseResult[0]);
this.setMonth(parseResult[1]);
...
public String toString() {
return "y =" + year + ", m =" + month + ",...
}
public int getY() {
return y;
}
// followed by lots of getters for: m, h, c, f, r, s, ...
Now for the second public class...
public class Totals {
private ArrayList<MonthData> months;
public static void main(String args[]) throws IOException, Exception {
Totals t = new Totals("..blah/../..blah/../Numbers.data");
}
public void readDataFile(String filename) throws IOException, Exception {
FileReader file = new FileReader(filename);
BufferedReader buffer = new BufferedReader(file);
String line;
buffer.readLine(); //skipping headers
...
while (!(line = buffer.readLine()).isEmpty()) {
this.months.add(new MonthData(line.trim()));
}
buffer.close();
System.out.println(this.months);
}
This class reads a file containing lots of data, here is a snippet of the data:
y m h c f r s //here for your reference
1930 1 8.1 2.4 6 120.5 54.2
1930 2 4.4 0.6 12 22.2 29.1
1930 3 8.1 2.1 9 76.2 88.2
...
When I System.out.println(this.months);
I get this:
y=1930, m=1, h=8.1, c=2.4, f=6, r=120.5, s=54.2, y =1930, m=2, h=4.4, c=0.6, f=12, r=22.2, s=29.1, ...
etc.
As you can see it corresponds with the data file so I know the data is being read to the ArrayList months
properly.
******** QUESTION ***********
Now what I want to do is look at this ArrayList and get every r value and store them in a different ArrayList, lets say ArrayList rValues
(so that i have an ArrayList full of r values only).
I know I need to iterate over this ArrayList somehow to the r value indexes, get the values and then store them in another ArrayList just dont know how!! :(
Any help here at all will be greatly appreciated. Happy to answer any questions, although i have possibly explained whats going on as best as i can. Thanks in advance guys :)
Upvotes: 2
Views: 2432
Reputation: 1334
Why don't you iterate over list like this:
for (int i = 0; i<months.size(); i++)
and then you can get your MonthData object with this command
months.get(i)
and if you want just a r value then create getter for r (getR()
) and call it and save in new array list:
Something like this:
ArrayList<Float> rValue = new ArrayList<>();
for (int i = 0; i<months.size(); i++)
{
rValue.add(months.get(i).getR());
}
(thanks to @Mick Mnemonic) You can also use foreach loop
ArrayList<Float> rValue = new ArrayList<>();
for (MonthData m: months)
{
rValue.add(m.getR());
}
Upvotes: 3