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
- Business Analyst: How to write accurate software requirements
- Business Analyst: A simple secret to running a great meeting
- One thing a business analyst should ask about any requirement
- Business Analysts and Use Case quality: Questions to ask yourself when writing a Use Case
- The three things a Business Analyst should think about during meetings
- Testing web applications Selenium with Scala 3 and ScalaTest
- Scala Cookbook 2021: A best-selling new release in OOP and FP
- Salar Rahmanian's newsletter (and Functional Programming, Simplified)
- Our “Back To Now” app: Now available on iOS and Android
- An Android location “Fused Location Provider API” example