Home > OS >  Summing Set values in Scala
Summing Set values in Scala

Time:03-06

I have a set of Tuples and I'd like to get sum of it's values integer part. But when I apply this code it returns 1, when 3 is expected. I suppose that it's because result of the map function also returns a Set and duplicate results are eliminated.

object Main:

  def main(args: Array[String]): Unit = {
    val pairs = Set(("one", 1), ("two", 1), ("three", 1))
    val sum = pairs.map(pair => pair._2).sum
    println(sum) //returns 1
  }

My expectations are based on how such things work in Java. Set has distinct elements, but Stream doesn't until distinct() or .collect(toSet()) are used. According to this the result is 3 as expected.

import org.apache.commons.lang3.tuple.Pair;

import java.util.Set;

public class Main {

    public static void main(String... args) {
        var pairs = Set.of(Pair.of("one", 1), Pair.of("two", 1), Pair.of("three", 1));
        var sum = pairs.stream()
                .map(Pair::getRight)
                .reduce(0, Integer::sum);
        System.out.println(sum); //returns 3
    }
}

My current assumptions on how to achieve such result (3) are:

  1. Convert Set to List, but it seems not to be a good solution:
 val sum = List.from(pairs).map(pair => pair._2).sum
  1. Use foldLeft:
val sum = set.foldLeft(0)((a, b) => a   b._2)

But maybe there are more convinient methods?

CodePudding user response:

You can use iterator or view to get required collection representation:

val sum = pairs.iterator.map(_._2).sum
  • Related