How to convert BitSet to binary string effectively?
So this is the most efficient way I have tried so far:
private static class FixedSizeBitSet extends BitSet {
private final int nbits;
public FixedSizeBitSet(final int nbits) {
super(nbits);
this.nbits = nbits;
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder(nbits);
IntStream.range(0, nbits).mapToObj(i -> get(i) ? '1' : '0').forEach(buffer::append);
return buffer.toString();
}
}
Or other way using more streams:
@Override
public String toString() {
return IntStream
.range(0, nbits)
.mapToObj(i -> get(i) ? '1' : '0')
.collect(
() -> new StringBuilder(nbits),
(buffer, characterToAdd) -> buffer.append(characterToAdd),
StringBuilder::append
)
.toString();
}