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")) )
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.
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.
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.
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With