relisher relisher - 1 year ago 59
Java Question

Find first index of matching character from two strings using parallel streams

Trying to figure out whether it is possible to find what the first index of a matching character that is within one string that is also in another string. So for example:

String test = "test";
String other = "other";
int value = get(test, other);
// method would return 1, as the first matching character in
// other, e is at index 1 of test

So I'm trying to accomplish this using parallel streams. I know I can find whether there is a matching character fairly simply like such:


How would I use this to find the exact index?

EDITED: edited to reflect correct index

Answer Source

You can do it by relying on String#indexOf(int ch), keeping only values >= 0 to remove non existing characters then get the first value.

// Get the index of each characters of test in other
// Keep only the positive values
// Then return the first match
// Or -1 if we have no match
int result = test.chars()
    .filter(i -> i >= 0)



NB 1: The result is 1 not 2 because indexes start from 0 not 1.

NB 2: Unless you have very very long String, using a parallel Stream in this case should not help much in term of performances because the tasks are not complexes and creating, starting and synchronizing threads has very high cost so you will probably get your results much slower than with a normal stream.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download