1

I have a collection of tuples:

Seq(("foo", "bar3"), ("foo", "bar1"), ("foo", "bar2"))

How do I apply such a function that I get

("foo", Seq("bar1", "bar2", "bar3"))

I just cannot wrap my head around this. I am new to functional programming so I was thinking about some sort of folding or aggregating.

3
  • Will the first element of the tuple always have the same value? Or do you want to collect together all the second elements that share the same value of the first element? And is the order of the Seq of second elements important? I note it isn't the order of the input sequence, and is sorted, but is that accidental or do you want it sorted? Commented Jul 6, 2016 at 15:06
  • @TheArchetypalPaul The order is not important. I want to collect together all the second elements that share the same value of the first element. Commented Jul 6, 2016 at 15:14
  • Thanks. Sergey's answer is a good 'un, then. Commented Jul 6, 2016 at 15:17

1 Answer 1

2

I guess your solution looks like this:

val seq = Seq(("foo", "bar3"), ("foo", "bar1"), ("foo", "bar2"))
seq.groupBy(_._1)
  .mapValues(_.map(_._2))
Sign up to request clarification or add additional context in comments.

2 Comments

@AlexandrDorokhin partially I agree with you. Made minor improvements in code
@AlexandrDorokhin But it works well, even with structure like Seq((foo, foo1, bar1),(foo, foo1, bar2),... (with replacing _._2 in the last line of code with custom mapping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.