簡體   English   中英

如何將字符串ArrayList轉換為Double ArrayList並計算值的總和?

[英]How to Convert a String ArrayList to a Double ArrayList and calculate the sum of values?

我想做的是

  1. 將我的字符串arraylist值添加到雙精度arraylist中。

  2. 計算雙精度數組列表中的值的總和

  3. 將總和值設置為TextView。


private ArrayList<String> totals = new ArrayList<>();
private ArrayList<Double> demototal = new ArrayList<>();
//Parsing the JSON String
try
{
total = itemData.getString(ParseBarcode.KEY_TOTAL);
}catch (JSONException e)
{
e.printStackTrace();
}
// add the parsed total to totals arraylist
totals.add(total);

//converting all values from totals array to Double and add to arraylist demototal
for (int i = 0; i < totals.size(); i++) 
{
final String value = totals.get(i);
double total_ary = (double)Math.round((Double.parseDouble(value))*100.0)/100.0;
demototal.add(total_ary);

Toast.makeText(AddInvEst.this, total_ary+"", Toast.LENGTH_SHORT).show();
}

//converting double value to string for setting it to sum textView.
 String amount = Double.toString(setArrayListElement(demototal));
 textViewSum.setText(amount);//set total text to amount

 //calculate amount here we pass setArrayListElement as Double arraylist
 private Double setArrayListElement(ArrayList inArray) {
 Double amount = 0.0d;
 for (int i = 0; i < inArray.size(); i++) {
 amount +=  Double.valueOf(Math.round((Double) inArray.get(i))*100.0)/100.0;
 }
 return amount;
 }

My string arraylist contains values like [51,073,29,620] which is a currency value.
    List<String> stringList = new ArrayList<>();
    stringList.add("1.2");
    stringList.add("2.3");
    stringList.add("3.4");
    double result = stringList.stream().collect(Collectors.summingDouble(string -> Double.parseDouble(string)));
List<String> stringList = new ArrayList<>();
stringList.add("2");
stringList.add("3");
stringList.add("5");

double[] doubleList = new double[StringList.size()]; 
double sum = 0;
for (int i = 0; i < StringList.size(); ++i) { 
    doubleList[i] = Double.parseDouble(StringList.get(i)); 
    sum += doubleList[i];
}

textView.setText(sum);

•使用DoubleStream – Java 1.8:

List<String> stringList = new ArrayList<>();
stringList.add( "1.2" );
stringList.add( "2.3" );
stringList.add( "3.4" );

double rslt = stringList.stream()
                .mapToDouble( s -> Double.parseDouble( s ) ).sum();

您只需要遍歷字符串列表:

double currValue = 0;
double sum = 0;
for(String s : strList) {
    currValue = Double.valueOf(s);
    doubleList.add(currValue);
    sum += currValue;
} 

暫無
暫無

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

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