I have a list of tuples, for example:
(0,2)
(0,5)
(2,0)
(2,5)
(3,4)
(4,3)
(5,0)
(5,2)
There are some tuples where (x, y)
You can groupBy
the tuples represented as a Set
, which will make Set(0, 5) == Set(5, 0)
, etc. Then map
the resulting Map
to the groups of tuples and convert it back to a List
, and finally grab the head
of each list for one representative of the group. Calling head
is ok here, because the groups will never be empty (they would otherwise just not be there at all).
val list = List((0,2), (0,5), (2,0), (2,5), (3,4), (4,3), (5,0), (5,2))
list.groupBy { case (x, y) => Set(x, y) } // Map[Set, List[(Set, (Int, Int))]]
.map(_._2) // Iterable[List[(Int, Int)]]
.toList // List[List[(Int, Int)]]
.map(_.head) // List[(Int, Int)]
res10: List[(Int, Int)] = List((0,5), (3,4), (2,5), (0,2))