Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge tuples by same elements in Scala

For example, if I have the following tuples:

(1, "a", "l")
(1, "a", "m")
(1, "a", "n")

I want to merge them like this:

(1, "a", List("l", "m", "n"))

In my case, the lists are a result from an inner join using Slick. So, the first and second elements (1 and "a") should be the same. If somebody knows how to merge like that in case of using Slick, let me know please.

Or more generally, the way to merge tuples with inner lists by the same elements.

(1, "a", "l")
(1, "a", "m")
(1, "b", "n")
(1, "b", "o")
// to like this
List( (1, "a", List("l", "m")), (1, "b", List("n", "o")) )
like image 396
Outsider Avatar asked Jun 04 '13 18:06

Outsider


People also ask

How to get elements of tuple in Scala?

Accessing the elementsOne way of accessing tuple elements is their positions. The individual elements are named _1 , _2 , and so forth. One way of accessing tuple elements is their positions. The individual elements are accessed with tuple(0) , tuple(1) , and so forth.

How to merge two lists into tuple?

To merge two lists into a list of tuples: Pass a lambda function and the two lists to the map() function. The lambda function should return a tuple containing the two list elements. Use the list() class to convert the map object to a list of tuples.

What is the maximum size of tuple in Scala?

Tuple are of type Tuple1 , Tuple2 ,Tuple3 and so on. There is an upper limit of 22 for the element in the tuple in the scala, if you need more elements, then you can use a collection, not a tuple.

What is the difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.


1 Answers

How about:

val l = ??? // Your list

val groups = l groupBy { case (a, b, c) => (a,b) }

val tups = groups map { case ((a,b), l) => (a,b,l.map(_._3)) }

tups.toList
like image 125
gzm0 Avatar answered Sep 28 '22 00:09

gzm0