×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala - Get multiple, unique, random elements from a list

By IncludeHelp Last updated : October 20, 2024

List in Scala

The list is an immutable collection of elements of the same data type. The thing that makes a List different from an array is that List is Linked List.

How to get multiple unique elements?

Multiple random unique elements is a set of elements (more than one) that are random element taken from a unique element of the list randomly.

Example

List = (10, 20, 10, 40, 10, 70, 20, 90)
Distinct elements of list = (10, 20, 40, 70, 90)
Multiple random elements(2) = (40, 90)

Program to find multiple random unique elements

object MyObject {
    def main(args: Array[String]) {
        val mylist = List(10, 20, 10, 40, 10, 20, 90, 70)
        println("Element of the list:\n" + mylist)
        println("Unique elements of the list:\n" + mylist.distinct)
        println("Multiple Random elmenets of the list:\n" + scala.util.Random.shuffle(mylist.distinct).take(2))
    }
}

Output

Element of the list:
List(10, 20, 10, 40, 10, 20, 90, 70)
Unique elements of the list:
List(10, 20, 40, 90, 70)
Multiple Random elmenets of the list:
List(20, 90)

Explanation

In this program, we are going to extract multiple unique random elements from the List. For this we have used 3 function, let's discuss them one by one.

  • distinct: the distinct method does exactly what its name suggests i.e. it rips off the duplicate elements and the new list will contain only unique elements.
  • shuffle: the shuffle method is a part of Random class the shuffles the elements of the list to a random arrangement.
  • take: the take method is used to take any number of elements from the list.

So, to extract our multiple unique random elements from the list we have first used the distinct to extract all unique elements. After this, we have shuffled the element using shuffle. so, while taking the element we will get random elements. Finally, we have used to take the method to select 2 elements from the List.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.