Thursday, 26 March 2015

Group By Sum Scala 2.11 vs Java 8

I had to recently implement an aggregate function in Scala 2.11 and Java 8... Which one do you prefer?

Scala 2.11
case class Datum(val id: String, val count: Int)

object GroupBySumScalaDemo {
  val list = List(Datum("a", 1), Datum("a", 2), Datum("a", 3),
                  Datum("b", 4), Datum("b", 5),
                  Datum("c", 6))
                  
  // Want to group by 'id' and sum all values
  val map = list.groupBy(_.id).mapValues(_.map(_.count).sum)   
  
  println(map)
  
  def main(args: Array[String]): Unit = {
  }
}
Java 8
class MyDatum {
  private final String id;
  private final int count;
 
  public MyDatum(final String id, final int count) {
    this.id = id;
    this.count = count;
    }

  public String getId() {
    return id;
  }

  public int getCount() {
    return count;
  }
}

public class GroupBySumJava8Demo {
  public GroupBySumJava8Demo() {
    final List list = Arrays.asList(
      new MyDatum("a", 1), new MyDatum("a", 2), new MyDatum("a", 3),
      new MyDatum("b", 4), new MyDatum("b", 5),
      new MyDatum("c", 6));
    final Map map = list.stream()
      .collect(Collectors.groupingBy(MyDatum::getId, Collectors.summingInt(MyDatum::getCount)));
    System.out.println(map);
  }

  public static void main(String[] args) {
    new GroupBySumJava8Demo();
  }
}
I know which one I like ;-)

1 comment:

Xavier Witdouck said...

What about in Perl? LOL! Yes Scala is much better :)

Blog Archive