简体   繁体   中英

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

What I am trying to do is

  1. Take my string arraylist values and add them to a double arraylist.

  2. Calculate the sum of the values in the double arraylist and

  3. Set the sum value to a 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);

• using a 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();

You just need to loop over the string list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM