BitSet &() Method in Scala with Example

Here, we will learn about &() method defined on BitSet in Scala. It is used to return the intersection of two BitSets. We will learn about &() method in Scala with syntax and examples.
Submitted by Shivang Yadav, on December 10, 2020

BitSet in Scala is a special collection of positive integers. Scala programming language has a huge library containing a lot of utility functions to help working with data structure easy.

BitSet &() method

BitSet &() method is used to find the intersection of two Bitsets. It performs 'and' operation of both Bitsets in Scala. It returns elements that are in both BitSets.

Syntax:

BitSet1 & (BitSet2)

Parameters:

The method accepts a BitSet as a parameter for finding an intersection.

Return Type:

It returns a BitSet which contains elements that are present in both BitSets.

Let's see some examples to understand the working of &() method on BitSets.

Example 1: Program to illustrate the working of &() method

// Program to illustrate the working of &() method

import scala.collection.immutable.BitSet

object MyObject {
    def main(args: Array[String]) {
        val BitSet1 = BitSet(4, 1, 6, 2, 9)
        val BitSet2 = BitSet(6, 3, 9, 12, 15)
        
        println("BitSet1 : " + BitSet1)
        println("BitSet2 : " + BitSet2)
        
        val resultBitSet = BitSet1 & (BitSet2)
        println("BitSet1 & BitSet2 : " + resultBitSet)
    }
}

Output:

BitSet1 : BitSet(1, 2, 4, 6, 9)
BitSet2 : BitSet(3, 6, 9, 12, 15)
BitSet1 & BitSet2 : BitSet(6, 9)

Explanation: In the above code, we have created two BitSets and printed their value. Then we have found the intersection of both using the &() method. Then print the value of it using println method.

Program 2: Program to illustrate the working of &() method on two BitSets with any common element

// Program to illustrate the working of &() method

import scala.collection.immutable.BitSet

object MyObject {
    def main(args: Array[String]) {
        val BitSet1 = BitSet(4, 1, 6, 2, 9)
        val BitSet2 = BitSet(3, 5, 7, 12, 16)
        
        println("BitSet1 : " + BitSet1)
        println("BitSet2 : " + BitSet2)
        
        val resultBitSet = BitSet1 & (BitSet2)
        println("BitSet1 & BitSet2 : " + resultBitSet)
    }
}

Output:

BitSet1 : BitSet(1, 2, 4, 6, 9)
BitSet2 : BitSet(3, 5, 7, 12, 16)
BitSet1 & BitSet2 : BitSet()

Explanation: In the above code, we have created two BitSets BitSet1 and BitSet2 and then we have printed their value. We have used the &() operation to find the interaction of both Bitsets and stored the result in a BitSet named resultBitSet with is printed on screen using println method.



Comments and Discussions!

Load comments ↻





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