Building on the 1st answer and providing a little extra perspective: you can can get grouping greater than 2 for the different combinations. Not sure what is req'd as question is a little vague.
val df = Seq(
(1, Seq(1, 2, 3, 4, 6)),
(2, Seq(2, 3, 4, 6, 7)),
(3, Seq(1, 2, 5, 9, 100)),
(4, Seq(11, 2, 4, 5, 7, 32, 44, 54)),(44, Seq(11, 2, 4, 5, 7, 32, 44, 654)),
(5, Seq(7, 12, 34, 32, 44, 54)),
(6, Seq(5, 21))
).toDF("passengerId", "trainId")
val df2 = df.as("d1").join(df.as("d2"), $"d1.passengerId" =!= $"d2.passengerId")
.selectExpr("d1.passengerId as passengerId1", "d2.passengerId as passengerId2", "d1.trainId as trainId1", "d2.trainId as trainId2")
.where("size(array_intersect(trainId1, trainId2)) > 3")
.selectExpr("array_sort(array(passengerId1, passengerId2)) as ar", "trainId1")
val df3 = df2.withColumn("res", expr("explode(trainId1)"))
val df4 = df3.groupBy("trainId1").agg(collect_set("ar").as("res"))
val df5 = df4.withColumn("passengerIDs", array_distinct(sort_array(flatten($"res"))))
df5.show()
returns:
+--------------------+-----------------+------------+
| trainId1| res|passengerIDs|
+--------------------+-----------------+------------+
| [1, 2, 3, 4, 6]| [[1, 2]]| [1, 2]|
| [2, 3, 4, 6, 7]| [[1, 2]]| [1, 2]|
|[11, 2, 4, 5, 7, ...|[[4, 44], [4, 5]]| [4, 5, 44]|
|[11, 2, 4, 5, 7, ...| [[4, 44]]| [4, 44]|
|[7, 12, 34, 32, 4...| [[4, 5]]| [4, 5]|
+--------------------+-----------------+------------+
which could be of use. It's actually quite a hard problem.