簡體   English   中英

遍歷ArrayList增加值

[英]Iterating over an ArrayList adding values

在此處輸入圖片說明 是否可以遍歷不是所有實例而是每12個實例添加一個ArrayList? 關於使用addAll來添加所有實例而不是部分的線程很多。

我目前有一個包含數百個浮點值的ArrayList:

片段:

120.5, 22.2, 76.2, 64.5, 38.3, 27.1, 149.4, 62.3, 127.9, 79.1, 83.4, 68.3, 61.0, 83.4, 5.4, 83.8, 78.3, 111.8, 104.1, 145.2, 94.3, 20.0, 104.7, 35.9, 68.6, 10.1, 41.1, 82.2, 170.7, 17.2, 122.1, 61.0, 46.3, 101.1, 59.0, 30.0, ...

我想要做的是將前12個實例求和,然后將總數加到新的ArrayList中,再將下12個實例求和,將其存儲到新創建的ArrayList中,依此類推。 恰好有996個實例,所以我應該在這個新的ArrayList中有83個新值(996/12 = 83)。

能做到嗎? 如果可以,怎么辦? 這是我必須去的地方...

  // ArrayList that contains the float values shown above

  public MonthData depthValues() {
    ArrayList<Float> rValue = new ArrayList<>();
    for (int i = 0; i<months.size(); i++)
    {
        rValue.add(months.get(i).getDepthMM());
    }
    System.out.println(rValue);
    System.out.println(rValue.size());
    return null;

  }

  //New arrayList im trying to make
  //probably done this wrong, help needed here

  public MonthData depthTotals() {
    ArrayList<Float> depthAdd = new ArrayList<Float>();

  int t = 12;

  for(int i = 0; i<rValue.size(); ++i)
  {
    ??????????????????
  }
  }

任何幫助將不勝感激,我似乎無法在任何地方找到任何東西,因為我認為所有實例的總和是如此受歡迎。 它可能是正確迭代的情況。 關於求和,我將在c ++中使用accumulate ,但不知道java中的等效項(如果有的話)。 預先感謝您的任何建議/協助!

更多代碼:

public class WeatherStation {
  private ArrayList<MonthData> months;
  private ArrayList<MonthData> rValue;
  private ArrayList<MonthData> depthAdd;

MonthData是用於讀取此類數據的模型,它包含許多吸氣劑。

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 MonthData depthValues() {
    ArrayList<Float> rValue = new ArrayList<>();
    for (int i = 0; i<months.size(); i++)
{
    rValue.add(months.get(i).getDepthMM());
}
System.out.println(rValue);
System.out.println(rValue.size());
return null;

}

推薦代碼:

 public MonthData depthTotals() {
    ArrayList<Float> depthAdd = new ArrayList<>();
    Iterator<Float> it = rValue.iterator();
    final int MAX = 12;
    while (it.hasNext()){
      float sum = 0f;
      int counter = 1;
      //iterating 12 times
      //still check if there is an element in list
      while (counter < MAX && it.hasNext()){
        sum += it.next();
        counter++;
      }
      depthAdd.add(sum);}
    }

問題: Iterator<Float> it = rValue.iterator();

類型不匹配:無法從Iterator<MonthData>轉換為Iterator<Float>

最好的方法是使用Iterator和使用while12計數器。 這是一個例子:

List<Float> yourList = ...;
// fill yourList
List<Float> results = new ArrayList<>();
Iterator<Float> it = yourList.iterator();
final int MAX = 12;
while (it.hasNext()) {
    float sum = 0f;
    int counter = 1;
    //iterating 12 times
    //still, check if there's an element in your list
    while (counter <= MAX && it.hasNext()) {
        sum += it.next();
        counter++;
    }
    result.add(sum);
}

我建議您使用doubleDouble而不是float,因為它的精度大約是六萬億倍。

您可以像這樣對每12個塊求和

public static List<Double> sumBlocks(List<Double> list, int blockSize) {
    List<Double> ret = new ArrayList<>();
    for(int i = 0; i < list.size(); i += blockSize) {
        double sum = 0;
        for(int j = 0, len = Math.min(list.size() - i, blockSize); j < len; j++)
            sum += list.get(i + j);
        ret.add(sum);
    }
    return ret;
}

並打電話

List<Double> sums = sumBlocks(list, 12);

只是為了演示實現此目的的另一種方法:

public static List<Double> sumBlocks(List<Double> list, int blockSize) {
    List<Double> result = new ArrayList<>();
    double sum = 0d;
    for (int i = 0; i < list.size(); i++) {
        if (i > 0 && i % blockSize == 0) {
            result.add(sum);
            sum = 0d;
        }
        sum += list.get(i);
    }
    result.add(sum);
    return result;
}

Arraylist對象從List類繼承sublist(start,end)方法。 您可以使用myList.sublist(i,j)訪問子列表並獲取總和。 從那里開始,只需簡單的算法即可獲得迭代。 在for循環內,它應該是:myList.sublist(i * 12,i * 12 + 12)。

//Input list
ArrayList<Float> inputList = new ArrayList<Float>();

ArrayList<Float> result = new ArrayList<Float>();
    int groupSize = 12;
    int offset=0;
    while(offset < inputList.size()) {
        int toIndex = (inputList.size()-offset)>=groupSize? offset+groupSize : inputList.size();
        result.add( listSum(inputList.subList(offset,  toIndex)) );
        offset += groupSize;
    }

在列表中添加項目的輔助方法

static float listSum(List<Float> ar) {
    float accumulator = 0f;
    for(float item:ar) {
        accumulator += item;
    }
    return accumulator;
}
Lista<Double> list = // original list
List<Double> ret = new ArrayList<>();

int counter = 0;
double sum = 0; 

for (Double f : list) {
   if (counter == 12) {
       sum = 0;
       counter = 0;
       ret.add(sum);
   }
   sum += f;
   counter++;
}
// if list is not a multiple of 12
if (list.size() % 12 != 0) {
    ret.add(sum);
}
return ret;

嘗試這個:

public float total;

for(int i; i < rValue.Size(); i ++)
{
     total += rValue[i];

if(i%12=0)
  {
     add total to new ArrayList
     total = 0;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM