1

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

4 Answers 4

3
    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)));
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1
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);

2 Comments

Thanks @Uma Kanth. :)
Thanks a lot @Madushan Perera
0

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;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.