Reputation: 1692
The *
character converts to true, everything else to false.
This answer shows how to convert to Boolean[], but I seek to convert to an array of scalar booleans.
java8 lambda: convert a String of 0's and 1's to basic array of booleans
Upvotes: 1
Views: 1547
Reputation: 298233
Consider using a BitSet
instead, which is the more efficient storage structure
BitSet bs = IntStream.range(0, string.length())
.filter(i -> string.charAt(i)=='*')
.collect(BitSet::new, BitSet::set, BitSet::or);
You can test the bits using bs.get(index)
, which is not worse than array[index]
.
Note that a BitSet
also has a stream()
method which produces an IntStream
of the indices of true
value, equivalent to the stream we used for constructing the BitSet
. So if you can’t get away without an array at some point, you could create it like
boolean[] array = new boolean[string.length()];
bs.stream().forEach(i -> array[i]=true);
Upvotes: 2
Reputation: 59112
If the requirements are simply to convert to the described boolean array and to use streams, you can do it like this:
boolean[] result = new boolean[string.length()];
IntStream.range(0, string.length()).forEach(n -> result[n] = (string.charAt(n)=='*'));
Upvotes: 7