简体   繁体   中英

JAVA Sum results from for loop of hashset

I have a hashset with start and endtimes, in my code i calculate the difference between them so my result is (in minutes): 60, 30, etc. Here is my question, how can i get the sum of all those results? So i want just one result with sum of every result (for example 90)

Below is the code without the counting thing i want

        for (Verhuur verhuur : verhuur)
    {
       //begin en eindtijd in variabelen stoppen
       String starttime = verhuur.Begintijd;
       String endtime = verhuur.Eindtijd;
       SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
       try
       {
        //begin en eindtijd pasrsen tot juist formaat   
        Date date1 = format.parse(starttime);
        Date date2 = format.parse(endtime);
        long difference = date2.getTime() - date1.getTime();
        System.out.println(difference/1000/60);
       }

       catch(Exception ex)
       {
        ex.printStackTrace();
       }  

    }

with some slight tidy up

  • dateformat is used for every one of the loops. You can instantiate outside for effiency
  • the for loop wouldnt compike becuase you had two verhuur. I presume one should be verhuurs
  • put total inside the for loop to add the minutes

    long totalMins = 0; final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); for (Verhuur verhuur : verhuurs) { Date date1 = format.parse(verhuur.begintijd); Date date2 = format.parse(verhuur.eindtijd); long difference = date2.getTime() - date1.getTime(); total += ((difference/1000)/60); } System.out.println("total is " + total);

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