Reviewing a Java code snippet

Souvik Sarkar
sounix000@gmail.com

November 9, 2020

API reference

For this section, I assumed that the method in the code sample is part of a class NeedlesInHaystack.

Class: NeedlesInHaystack

This class provides functionality to search for multiple needle strings within a single haystack string and outputs the frequency of each needle’s occurrence.

Method: findNeedles

Example

String haystack = "Google Cloud provides APIs to use Google's ML/AI capabilities.";
String[] needles = {"Google", "API", "documentation", "AWS", "ML/AI"};
new NeedlesInHaystack().findNeedles(haystack, needles);

Output

Google: 2
API: 0
documentation: 0
AWS: 0
ML/AI: 1

Suggestions for code improvement

After reviewing the code sample, I have the following suggestions for improvement:

Suggested code

Here is the revised code, which incorporates the suggested improvements for efficiency and clarity:

public class NeedlesInHaystack {
    public static void findNeedles(String haystack, String[] needles) {
        // Store the length of the needles array in a variable
        int needlesLength = needles.length;

        // Split the haystack string once
        String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);

        // Create an array to store the frequency counts
        int[] countArray = new int[needlesLength];

        // Iterate through the needles and count their occurrences
        for (int i = 0; i < needlesLength; i++) {
            for (int j = 0; j < words.length; j++) {
                if (words[j].compareTo(needles[i]) == 0) {
                    countArray[i]++;
                }
            }
        }

        // Print the results
        for (int k = 0; k < needlesLength; k++) {
            System.out.println(needles[k] + ": " + countArray[k]);
        }
    }

    public static void main(String[] args) {
        // Hard-coded values for demonstration
        // Ideally, values should be received from standard input
        String haystack = "Google Cloud provides APIs to use Google's ML/AI capabilities.";
        String[] needles = {"Google", "API", "documentation", "AWS", "ML/AI"};
        findNeedles(haystack, needles);
    }
}

Sample output

Google: 2
API: 0
documentation: 0
AWS: 0
ML/AI: 1

Comments