Scala Saturday – The Stream.distinct Method

Scala Saturday today is short and sweet: Stream.distinct. Stream.distinct removes any duplicate members of a stream, leaving only unique values.

One way to remove duplicates is to turn your stream into a set with Stream.toSet:

val noDupes = Stream(3,5,6,3,3,7,1,1,7,3,2,7).toSet
// noDupes: scala.collection.immutable.Set[Int] = 
//   Set(5, 1, 6, 2, 7, 3)

That’s fine if you don’t care about preserving the order of the items in the input stream.

But if you do want to preserve the order, Stream.distinct is the ticket:

val noDupesOrdered =
    Stream(3,5,6,3,3,7,1,1,7,3,2,7).distinct
// noDupesOrdered: scala.collection.immutable.Stream[Int] = 
//   Stream(3, 5, 6, 7, 1, 2)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.