从 ArrayList 访问索引值并将它们存储在单独的新 ArrayList 中

Accessing index values from an ArrayList and storing them in a seperate new ArrayList

我目前有一个 ArrayList 叫做月。

ArrayList<MonthData> months;

MonthData 是一个 class,基本上是数据模型。

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

现在是第二个 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);
  }

这 class 读取一个包含大量数据的文件,这里是数据的片段:

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

当我System.out.println(this.months);

我明白了:

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

如您所见,它与数据文件相对应,所以我知道数据正在正确读取到 ArrayList months

******** 问题 *********** 现在我想要做的是查看这个 ArrayList 并 获取每个 r 值并将它们存储在不同的 ArrayList 中,假设 ArrayList rValues (这样我就有一个仅包含 r 值的 ArrayList)。

我知道我需要以某种方式遍历此 ArrayList 到 r 值索引,获取值,然后将它们存储在另一个 ArrayList 中,只是不知道如何!! :(

我们将不胜感激任何帮助。很高兴回答任何问题,尽管我可能已经尽我所能解释了发生的事情。提前谢谢大家:)

你为什么不像这样遍历列表:

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

然后您可以使用此命令获取您的 MonthData 对象

months.get(i)

如果您只想要一个 r 值,则为 r (getR()) 创建 getter 并调用它并保存在新的数组列表中:

像这样:

ArrayList<Float> rValue = new ArrayList<>();
for (int i = 0; i<months.size(); i++)
{
    rValue.add(months.get(i).getR());
}

(感谢@Mick Mnemonic) 您还可以使用 foreach 循环

ArrayList<Float> rValue = new ArrayList<>();
for (MonthData m: months) 
{ 
    rValue.add(m.getR()); 
}