Reputation: 11
Let's say I want to search the occurrence of a word in a string in a parallel way. Say for example we have a string "Hello i am bob and my name is bob" and a word "bob". The function needs to return 2.
Achieving this sequentially is pretty easy. We just need to use a for loop to go over our string and count whenever our word matches another word in the string.
I am trying to solve this using parallelism. I thought about splitting the string on every white space and passing the word to each thread, which then will check if it matches our searched word. However, looking for white spaces in our string is still being done sequentially. So, parallelism can not be beneficial here.
Is there any other way to achieve this?
Upvotes: 1
Views: 330
Reputation: 4426
You can do str.indexOf(“bob”) != str.lastIndexOf(“bob”). If it’s not equal, you got two. You can do another check by removing first bob and the last bob becomes the first index, if you find another one by indexOf != lastIndexOf, you remove the first one again and continue searching until you are done. I’m sure there will be a way to still make this better.
Upvotes: 0
Reputation: 12937
This is not a problem to be solved with fork join since this is not recursive action. Stream api is the way to go here:
String str = "Hello i am bob and my name is bob";
long count = Arrays.stream(str.split("\\s+"))
.parallel()
.filter(s -> s.equals("bob"))
.count();
System.out.println("Bob appeared " + count + " times");
Upvotes: 1