C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Distinct: We invoke the distinct function on the furniture list. A new list, with duplicates removed, is returned.
Scala program that removes duplicates from list
// Create a list of strings.
val furniture = List("chair", "bed", "table", "table", "couch")
// Get distinct strings.
// ... This removes duplicates but retains order.
val result = furniture.distinct
// Print results.
println(furniture)
println(result)
Output
List(chair, bed, table, table, couch)
List(chair, bed, table, couch)
ToSet: This converts the list to a set. Duplicates are removed because a set cannot store duplicates.
ToList: We convert the set back into a list. Please note that ordering may be changed by the set.
ListScala program that uses toSet, toList
// Create a list of Ints.
val ids = List(10, 10, 1, 2, 3, 3)
println(ids)
// Convert list to set.
// ... Duplicate elements are removed at this step.
val set = ids.toSet
println(set)
// Convert set to list.
val ids2 = set.toList
println(ids2)
Output
List(10, 10, 1, 2, 3, 3)
Set(10, 1, 2, 3)
List(10, 1, 2, 3)
Here: We use a lambda expression to map all strings to uppercase forms. A more complex method could be applied.
Scala program that uses map and distinct
val codes = List("abC", "Abc", "ABC", "xyz", "XyZ")
println(codes)
// Convert all strings to uppercase.
// ... Then get distinct strings.
val result = codes.map(_.toUpperCase()).distinct
println(result)
Output
List(abC, Abc, ABC, xyz, XyZ)
List(ABC, XYZ)