1

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

8
  • do you want to use lambdas? Commented Aug 1, 2017 at 22:49
  • 5
    This is actually going to be highly difficult. The best solution I can think of is collectingAndThen(toList(), boxedBooleanListToArray) or the like. Commented Aug 1, 2017 at 22:49
  • @travisjayday yes Commented Aug 1, 2017 at 22:50
  • 2
    Sure: there's not going to be a better way than converting to a Boolean[] or a List<Boolean> and then converting that to a primitive boolean[], and you'll have to write that part yourself (or get it from a third-party library). Commented Aug 1, 2017 at 23:03
  • 5
    Converting to an array of boolean primitive type is a waste of resources. It's much better to use a BitSet. Do you need a boolean[] for any special reason? Commented Aug 2, 2017 at 2:42

2 Answers 2

7

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)=='*'));
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

Holger, I was terribly slow with this question (actually I'm having a SO break), but I had in mind exactly this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.