duckertito duckertito - 7 days ago 6
Scala Question

Get list with unique sub-lists

I have a list of lists and I want to get the list with only unique sub-lists. For instance, this input:

List((123,List(List(xxx, abc),List(xxx,abc),List(yyy,abc))),
(333,List(List(xxx, abc),List(yyy,abc),List(yyy,abc))))


should be converted into:

List((123,List(List(xxx,abc),List(yyy,abc))),
(333,List(List(xxx, abc),List(yyy,abc))))


I tried this:

val unique = input.map(list => (list._1, list._2.distinct))


but it does not do the expected trick. What am I doing wrong?

Answer

Just map and do distinct on the inner list.

mainList.map { case (a, list) => a -> list.distinct }

As your mainList consists of tuples, you can also use the tuple _2 to get the list in the tuple.

mainList.map(pair => pair._1 -> pair._2.distinct)

distinct will take care of keeping only the unique elements in the list.