The given code defines a Java method called `extractKeyValues` that...

September 2, 2025 at 03:27 PM

private static Map<String, String> extractKeyValues(String[] lines, String keySpec) { Map<String, String> keys = new LinkedHashMap<>(); if (keySpec == null || keySpec.isBlank()) return keys; // Parse keys from "customer_id:string-order_id:number" Set<String> keyNames = new LinkedHashSet<>(); for (String part : keySpec.split("-")) { String[] pair = part.split(":"); if (pair.length > 0) { String keyName = pair[0].trim().replace("\"", ""); if (!keyName.isBlank()) { keyNames.add(keyName); } } } // Search for each key name in the blob and extract value for (String keyName : keyNames) { boolean found = false; for (int i = 0; i < lines.length - 4; i++) { String line = lines[i].trim(); if (line.matches("\"?" + Pattern.quote(keyName) + "\"?\\s*:\\s*\\{\\s*")) { for (int j = i + 1; j < i + 5 && j < lines.length; j++) { String valLine = lines[j].trim(); if (valLine.contains("\"#text\"")) { String val = extractBetweenQuotes(valLine); keys.put(keyName.toUpperCase(), val); found = true; break; } } break; } } if (!found) { System.out.println("Could not find value for key: " + keyName); } } return keys; }

The given code defines a Java method called extractKeyValues that extracts specific key-value pairs from a collection of lines of text. Here's what it does, step by step:

Function Inputs:

  1. lines: An array of strings, which represents the text input where the extraction will be performed. Each string in the array is treated as a line.
  2. keySpec: A specification of the keys to extract, represented as a single string in a specific format (e.g., "customer_id:string-order_id:number"). Each key name is specified alongside its type (though the type is ignored in this function).

Function Outputs:

  • A Map<String, String> where the keys are uppercase versions of key names (from keySpec), and the values are the corresponding extracted string values from the input lines.
  • If a key's value cannot be found in the lines, a message is printed to indicate this.

Key Steps in the Code:

  1. Early Exit for Empty keySpec:

    • If keySpec is null or blank, an empty LinkedHashMap is returned immediately.
  2. Extract Key Names from keySpec:

    • The keySpec string is parsed to extract key names. For example, the specification "customer_id:string-order_id:number" is split into parts using "-" as a delimiter. Each part is then split further with ":" to isolate the key name (ignoring the type). These key names are added to a Set (keyNames) to ensure uniqueness.
  3. Search and Extract Values:

    • For every key name in keyNames, the method looks for a line in lines that matches the pattern of that key. It assumes that valid keys are followed by a JSON-like structure, such as:
      "customer_id": {
          "#text": "12345"
      }
      
    • Specifically, the method:
      • Searches for a line that matches the key name (e.g., "customer_id": {).
      • If such a line is found, it looks at the next few lines (up to 4) for a line containing "#text", which is assumed to hold the actual value.
      • The value is extracted using the helper method extractBetweenQuotes, which retrieves the string enclosed in quotes.
      • The extracted value is added to the keys map with the key name in uppercase as the map key.
  4. Handle Missing Keys:

    • If a key name is not found in the input lines, an error message is printed to indicate that the value for the key could not be located.
  5. Return Results:

    • Finally, the method returns the keys map containing the extracted key-value pairs.

Key Features:

  • The method assumes the input follows a JSON-like structure for keys and values.
  • Keys are case-insensitively processed (converted to upper case).
  • Logging is used to inform the caller when a key's value could not be found.

Example:

Input:

String[] lines = {
   "\"customer_id\": {",
   "    \"#text\": \"12345\"",
   "}",
   "\"order_id\": {",
   "    \"#text\": \"67890\"",
   "}"
};
String keySpec = "customer_id:string-order_id:number";

Output:

The returned map would be:

{ "CUSTOMER_ID" -> "12345", "ORDER_ID" -> "67890" }

Notes:

  1. If keySpec doesn't contain any valid keys or if the keys cannot be located in lines, the map remains empty or partially filled, with corresponding error messages printed.
  2. The helper method extractBetweenQuotes is critical, but its implementation is not provided. Likely, it extracts a substring surrounded by double quotes (").

Summary:

The extractKeyValues method extracts key-value pairs from a structured text (passed as an array of lines) based on a provided key specification string. It is designed to work with JSON-like data and supports logging for missing keys.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node