Aqsa Zahoor
Aqsa Zahoor

Reputation: 35

How to compare sublists in List[List[Double]]

I have a List[List[Double]]

Ignoring the last element of each list with in outer list, I want to compare inner lists i.e. we have a

List(
  List(0.1,0.5,0.3,0),
  List(2.3,0.1,0.4,1),
  List(0.1,0.5,0.3,1)
)

I want distinct list ignoring last element i.e.

List(
  List(0.1,0.5,0.3,0),
  List(2.3,0.1,0.4,1)
)

Here the 1st and last lists are similar ignoring the last elements. kindly provide me some clue. As I am very new to scala.

Upvotes: 1

Views: 95

Answers (2)

Leo C
Leo C

Reputation: 22449

If you're on Scala 2.13+ please see @jwvh's solution, otherwise ...

You could traverse the list via foldLeft to assemble a new list of inner lists by checking against a Set of lists with distinct init:

val list = List(List(0.1, 0.5, 0.3, 0.0), List(2.3, 0.1, 0.4, 1.0), List(0.1, 0.5, 0.3, 1.0))

list.foldLeft((List[List[Double]](), Set[List[Double]]())){ case ((ls, s), l) =>
  val lInit = l.init
  if (s.contains(lInit)) (ls, s) else (l :: ls, s + lInit)
}._1.reverse
// res1: List[List[Double]] = List(List(0.1, 0.5, 0.3, 0.0), List(2.3, 0.1, 0.4, 1.0))

In case order of the resulting inner lists is unimportant, an alternative is to group the list by the inner list's init, followed by extracting the first inner list from the grouped Map values:

list.groupBy(_.init).map(_._2.head) 
// res2: List[List[Double]] = List(List(2.3, 0.1, 0.4, 1.0), List(0.1, 0.5, 0.3, 0.0))

Upvotes: 2

jwvh
jwvh

Reputation: 51271

Study the Standard Library. It's amazing the things you can find there.

List(List(0.1,0.5,0.3,0),List(2.3,0.1,0.4,1),List(0.1,0.5,0.3,1)).distinctBy(_.init)
//res0: List[List[Double]] = List(List(0.1, 0.5, 0.3, 0.0), List(2.3, 0.1, 0.4, 1.0))

Upvotes: 7

Related Questions