0

I have an char array, and I want to get the number of the '^' char in that array. so if the array was '.', '.', '^', '-', '^' it would return 2. My plan was to make a new array that just contains the '^' char and then get the length of that array. I know this could be easily done with a for loop that loops over the array, but I think it would be cool to use streams as I've just started learning about them and want more practice, and I think it would be hilarious to have a single massive line instead of a few lines for a for loop and if statement. (this code does not need to be readable)

I have tried

char[] tentsInRow = IntStream.range(0, arr.length)
    .filter(n -> n == '^')
    .mapToObj(m -> arr[m]).toArray();

and

char[] tentsInRow = new String(getRow(i))
    .chars()
    .mapToObj(n -> (char)n)
    .filter(n -> n.equals('^'))
    .toArray();

getRow(i) returns a char array, and arr from the first line is the same thing

both of which give me the error: Required type: char[] Provided: Object[]

I saw there was a toArray(IntFunction<a[]> generator) function I could use that I thought could work, but I wasn't sure how to use it.

Does anyone know how I can convert from an Object array to a char array in this line, or know any other way to do this with streams/lambdas? I can also just do it the boring way with a for loop, just thought this would be cool lol. First post here so go easy

3
  • 3
    It is not hilarious to have your code in a new line (I'm sure most will agree). To make it readable, I've edited your question, making it multi-line. Commented Mar 27, 2023 at 12:42
  • 1
    "My plan was to make a new array that just contains the '^' char and then get the length of that array" - why, if you can just count? Commented Mar 27, 2023 at 12:44
  • 4
    An hilarious way to do it: java 8 stream using filter and count Commented Mar 27, 2023 at 12:44

1 Answer 1

1

If all you need is the number of '^' characters why not use .count?

long numberOfChars = IntStream.range(0, arr.length)
    .mapToObj(i -> arr[i])
    .filter(n -> n == '^')
    .count();
Sign up to request clarification or add additional context in comments.

1 Comment

No need for boxing: IntStream.range(0, arr.length).filter(i -> arr[i] == '^') .count();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.