What is BitSet.stream() in Java?

stream() is an instance method of BitSet which returns a stream of indices having the bit value set, i.e., true in the BitSet object. The indices returned are in order from lowest to the highest. The size of the stream is equal to the value returned by the cardinality() method.

The stream method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, check the following import statement.

import java.util.BitSet;

Syntax


public IntStream stream()

Parameters

The method has no parameters.

Return value

This method returns a stream of integers.

Code

Let’s have a look at an example.

import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Set the bit at index 3
bitSet.set(3);
bitSet.set(6);
// stream of indices at which bit is set
bitSet.stream().forEach(index -> System.out.println("Set Bit found at index " + index));
}
}

Free Resources