I am trying to find whether a specific string value is found within a 2D LinkedHashSet I have created.
Here is some code for the initialization of the LinkedHashSet:
LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<LinkedHashSet<String>>();
I have tried using .contains like this but it seems to be an incorrect argument type:
int N = Integer.parseInt(b1.readLine());
for(int i = 0; i<N; i++) {
String sorts [] = (b1.readLine()).split(" ");
if(block.stream().anyMatch(list->list.contains(sorts[0]))) {
//System.out.println("I entered");
for (Set<String> innerSet : block) {
for (String string : innerSet) {
if(string.equals(sorts[0])) {
innerSet.add(sorts[5]);
}
if(string.equals(sorts[5])) {
innerSet.add(sorts[0]);
}
}
}
}
else {
block.add(new LinkedHashSet<String>(Arrays.asList(sorts[0], sorts[5])));
}
You can use parallelSteam
to make the process concurrent and fast -
block.parallelStream()
.filter(stringSet ->
stringSet.contains(input))
.collect(Collectors.toList()).size() > 0
The code above takes block
(LinkedHashSet<LinkedHashSet<String>>
) and the input
string. Uses multiple thread from fork join pool to find input string in different sets. Finally it collects all such sets which contains input string and checks the size if it's more than 0 and return true if that is the case, false otherwise.
better version
is this -
block.parallelStream().anyMatch(strings -> strings.contains(input))
this is much more efficient because it will only wait for first match and immediately returns true.
anyMatch
javadoc -
* Returns whether any elements of this stream match the provided * predicate. May not evaluate the predicate on all elements if not * necessary for determining the result. If the stream is empty then * {@code false} is returned and the predicate is not evaluated.