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 ListI know which one I like ;-)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(); } }
1 comment:
What about in Perl? LOL! Yes Scala is much better :)
Post a Comment