How to calculate the sum of a List in Java and Scala
As a quick note about a difference between Java and Scala, I recently wrote this blog post about How to Sum the Elements of a List in Java (ArrayList, LinkedList, etc.). For several years I have known that in Scala you sum the contents of a List
like this:
// create a List val nums = List(1,2,3) // get the sum of the List val total = nums.sum
So it was a real surprise that as I was working on a Java/Android app, I had to write this much code to get the sum of a Java List
:
public static int sum (List<Integer> list) { int sum = 0; for (int i: list) { sum += i; } return sum; }
I haven’t worked with Java since I discovered Scala, so when I got back to using Java this was a big surprise.
As I note in my other blog post, in production Java code I recommend using the Apache Commons libraries to calculate the sum of a
List
, or possibly the new Java 8 stream reduction techniques, which I don’t know well yet.
Recent blog posts
- Free Scala and functional programming video training courses
- Free: Introduction To Functional Programming video training course
- The #1 functional programming (and computer programming) book
- The User Story Mapping Workshop process
- Alvin Alexander, Certified Scrum Product Owner (CSPO)
- Alvin Alexander is now a Certified ScrumMaster (CSM)
- Our “Back To Then” app (for iOS and Android)
- A Docker cheat sheet
- Pushing a Scala 3 JAR/Docker file to Google Cloud Run
- Reading a CSV File Into a Spark RDD (Scala Cookbook recipe)