### Build and Use Content Filtering System in Java Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt This example shows how to build a content filter using AhoCorasickDoubleArrayTrie, censor prohibited content, analyze categories, and save/load the filter. It requires a Map of words to categories for building the trie. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie.Hit; import java.io.*; import java.util.*; public class ContentFilter { private AhoCorasickDoubleArrayTrie filterTrie; public void buildFilter(Map wordCategories) { filterTrie = new AhoCorasickDoubleArrayTrie<>(); filterTrie.build(new TreeMap<>(wordCategories)); } public void loadFilter(String path) throws IOException, ClassNotFoundException { filterTrie = new AhoCorasickDoubleArrayTrie<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(path))) { filterTrie.load(in); } } public void saveFilter(String path) throws IOException { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path))) { filterTrie.save(out); } } public boolean containsProhibitedContent(String text) { return filterTrie.matches(text.toLowerCase()); } public String censorContent(String text) { StringBuilder result = new StringBuilder(text); List> hits = filterTrie.parseText(text.toLowerCase()); // Process in reverse order to maintain correct positions Collections.reverse(hits); for (Hit hit : hits) { String replacement = "*".repeat(hit.end - hit.begin); result.replace(hit.begin, hit.end, replacement); } return result.toString(); } public Map analyzeContent(String text) { Map categoryCounts = new HashMap<>(); filterTrie.parseText(text.toLowerCase(), (begin, end, category) -> { categoryCounts.merge(category, 1, Integer::sum); }); return categoryCounts; } public static void main(String[] args) throws Exception { ContentFilter filter = new ContentFilter(); // Build filter with word -> category mapping Map dictionary = new HashMap<>(); dictionary.put("spam", "advertising"); dictionary.put("buy now", "advertising"); dictionary.put("free money", "scam"); dictionary.put("password", "security"); dictionary.put("credit card", "security"); filter.buildFilter(dictionary); // Test content filtering String testContent = "Get free money! Buy now and share your password!"; System.out.println("Contains prohibited: " + filter.containsProhibitedContent(testContent)); // Output: Contains prohibited: true System.out.println("Censored: " + filter.censorContent(testContent)); // Output: Censored: Get **********! ******* and share your ********! System.out.println("Categories: " + filter.analyzeContent(testContent)); // Output: Categories: {advertising=1, security=1, scam=1} // Save and reload filter filter.saveFilter("/tmp/filter.dat"); filter.loadFilter("/tmp/filter.dat"); System.out.println("Filter reloaded, size: " + filter.filterTrie.size()); // Output: Filter reloaded, size: 5 } } ``` -------------------------------- ### Perform exact key lookup Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use get to retrieve values for exact keys, similar to a standard Map lookup. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap wordFrequency = new TreeMap<>(); wordFrequency.put("the", 1000); wordFrequency.put("and", 800); wordFrequency.put("that", 500); AhoCorasickDoubleArrayTrie trie = new AhoCorasickDoubleArrayTrie<>(); trie.build(wordFrequency); // Exact lookup System.out.println(trie.get("the")); // Output: 1000 System.out.println(trie.get("and")); // Output: 800 System.out.println(trie.get("th")); // Output: null (partial match doesn't count) System.out.println(trie.get("there")); // Output: null (not in dictionary) ``` -------------------------------- ### size - Get Dictionary Size Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Returns the number of keywords in the trie. Useful for validation and statistics. ```APIDOC ## size - Get Dictionary Size ### Description Returns the number of keywords in the trie. Useful for validation and statistics. ### Method `GET` (conceptual, as this is a method call on an object) ### Endpoint N/A (This is a method within the AhoCorasickDoubleArrayTrie class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; // Build trie TreeMap map = new TreeMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); System.out.println("Dictionary contains " + acdat.size() + " keywords"); // Output: Dictionary contains 3 keywords // Empty trie AhoCorasickDoubleArrayTrie emptyTrie = new AhoCorasickDoubleArrayTrie<>(); emptyTrie.build(new TreeMap<>()); System.out.println("Empty trie size: " + emptyTrie.size()); // Output: Empty trie size: 0 ``` ### Response #### Success Response (int) - **size** (int) - The number of keywords currently stored in the trie. #### Response Example ``` Dictionary contains 3 keywords Empty trie size: 0 ``` ``` -------------------------------- ### exactMatchSearch - Get Index for Perfect Hashing Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Searches for an exact key match and returns its internal index. Returns -1 if not found. The index can be used with get(int index) for O(1) value retrieval, acting as a perfect hash function. ```APIDOC ## exactMatchSearch - Get Index for Perfect Hashing ### Description Search for an exact key match and return its internal index. Returns -1 if not found. The index can be used with get(int index) for O(1) value retrieval, acting as a perfect hash function. ### Method `GET` (conceptual, as this is a method call on an object) ### Endpoint N/A (This is a method within the AhoCorasickDoubleArrayTrie class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap map = new TreeMap<>(); map.put("apple", "fruit"); map.put("banana", "fruit"); map.put("carrot", "vegetable"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); // Get index for a key (perfect hash) int appleIndex = acdat.exactMatchSearch("apple"); int bananaIndex = acdat.exactMatchSearch("banana"); int unknownIndex = acdat.exactMatchSearch("grape"); System.out.println("apple index: " + appleIndex); // Output: apple index: 0 System.out.println("banana index: " + bananaIndex); // Output: banana index: 1 System.out.println("grape index: " + unknownIndex); // Output: grape index: -1 // Use index for O(1) value retrieval if (appleIndex >= 0) { String value = acdat.get(appleIndex); System.out.println("Value at index: " + value); // Output: Value at index: fruit } ``` ### Response #### Success Response (int) - **index** (int) - The internal index of the key if found, otherwise -1. #### Response Example ``` apple index: 0 banana index: 1 grape index: -1 Value at index: fruit ``` ``` -------------------------------- ### Parse Text - Find All Matches (List Return) Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Parses input text and returns all pattern matches as a list of Hit objects. Each Hit includes the match's start and end indices, and its associated value. Suitable for collecting all matches. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie.Hit; import java.util.List; import java.util.TreeMap; // Build trie with keywords TreeMap map = new TreeMap<>(); map.put("hers", "hers"); map.put("his", "his"); map.put("she", "she"); map.put("he", "he"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); // Parse text and get all matches String text = "ushers"; List> hits = acdat.parseText(text); // Process results for (Hit hit : hits) { String matched = text.substring(hit.begin, hit.end); System.out.printf("Found '%s' at [%d:%d] with value: %s%n", matched, hit.begin, hit.end, hit.value); } // Output: // Found 'she' at [1:4] with value: she // Found 'he' at [2:4] with value: he // Found 'hers' at [2:6] with value: hers ``` -------------------------------- ### Perform Exact Match Search with AhoCorasickDoubleArrayTrie Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use exactMatchSearch to retrieve an internal index for a key, which can then be used for O(1) value retrieval via the get method. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap map = new TreeMap<>(); map.put("apple", "fruit"); map.put("banana", "fruit"); map.put("carrot", "vegetable"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); // Get index for a key (perfect hash) int appleIndex = acdat.exactMatchSearch("apple"); int bananaIndex = acdat.exactMatchSearch("banana"); int unknownIndex = acdat.exactMatchSearch("grape"); System.out.println("apple index: " + appleIndex); // Output: apple index: 0 System.out.println("banana index: " + bananaIndex); // Output: banana index: 1 System.out.println("grape index: " + unknownIndex); // Output: grape index: -1 // Use index for O(1) value retrieval if (appleIndex >= 0) { String value = acdat.get(appleIndex); System.out.println("Value at index: " + value); // Output: Value at index: fruit } ``` -------------------------------- ### Build and Parse Text Source: https://github.com/hankcs/ahocorasickdoublearraytrie/blob/master/README.md Initialize the trie with a map of keywords and parse text to find matches. ```java // Collect test data set TreeMap map = new TreeMap(); String[] keyArray = new String[] { "hers", "his", "she", "he" }; for (String key : keyArray) { map.put(key, key); } // Build an AhoCorasickDoubleArrayTrie AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie(); acdat.build(map); // Test it final String text = "uhers"; List> wordList = acdat.parseText(text); ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/hankcs/ahocorasickdoublearraytrie/blob/master/README.md Include the library in your project using Maven. ```xml com.hankcs aho-corasick-double-array-trie 1.2.3 ``` -------------------------------- ### Parse text with IHitFull callback Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Uses the IHitFull interface to retrieve match positions and a unique keyword index during text parsing. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap map = new TreeMap<>(); map.put("cat", "animal"); map.put("catalog", "book"); map.put("category", "classification"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); char[] text = "The catalog has every category of cat food".toCharArray(); // IHitFull provides the keyword index for perfect hashing acdat.parseText(text, new AhoCorasickDoubleArrayTrie.IHitFull() { @Override public void hit(int begin, int end, String value, int index) { String matched = new String(text, begin, end - begin); System.out.printf("Match: '%s' -> %s (index=%d)%n", matched, value, index); } }); // Output: // Match: 'cat' -> animal (index=0) // Match: 'catalog' -> book (index=1) // Match: 'cat' -> animal (index=0) // Match: 'category' -> classification (index=2) // Match: 'cat' -> animal (index=0) ``` -------------------------------- ### Add Gradle Dependency Source: https://github.com/hankcs/ahocorasickdoublearraytrie/blob/master/README.md Include the library in your project using Gradle Kotlin DSL. ```kotlin implementation("com.hankcs:aho-corasick-double-array-trie:1.2.2") ``` -------------------------------- ### Find the first match Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use findFirst to retrieve the first occurrence of a pattern, returning a Hit object or null if no match is found. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie.Hit; import java.util.HashMap; HashMap keywords = new HashMap<>(); keywords.put("urgent", "high-priority"); keywords.put("asap", "high-priority"); keywords.put("important", "medium-priority"); AhoCorasickDoubleArrayTrie trie = new AhoCorasickDoubleArrayTrie<>(); trie.build(keywords); String email = "Please review this important document asap"; Hit firstMatch = trie.findFirst(email); if (firstMatch != null) { System.out.printf("First keyword found: '%s' at position %d, priority: %s%n", email.substring(firstMatch.begin, firstMatch.end), firstMatch.begin, firstMatch.value); // Output: First keyword found: 'important' at position 19, priority: medium-priority } else { System.out.println("No keywords found"); } // When no match exists Hit noMatch = trie.findFirst("Regular message"); System.out.println(noMatch == null ? "No match" : noMatch.value); // Output: No match ``` -------------------------------- ### parseText with IHitFull - Extended Match Information Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Parse text using the `IHitFull` callback, which provides an additional index parameter. This index can serve as a perfect hash value for the matched keyword, enabling advanced lookup scenarios. ```APIDOC ## parseText with IHitFull - Extended Match Information ### Description Parse text using the IHitFull callback that provides an additional index parameter. The index can be used as a perfect hash value for the matched keyword, useful for advanced lookup scenarios. ### Method N/A (This is a method within the AhoCorasickDoubleArrayTrie class, not a REST endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap map = new TreeMap<>(); map.put("cat", "animal"); map.put("catalog", "book"); map.put("category", "classification"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); char[] text = "The catalog has every category of cat food".toCharArray(); // IHitFull provides the keyword index for perfect hashing acdat.parseText(text, new AhoCorasickDoubleArrayTrie.IHitFull() { @Override public void hit(int begin, int end, String value, int index) { String matched = new String(text, begin, end - begin); System.out.printf("Match: '%s' -> %s (index=%d)%n", matched, value, index); } }); // Output: // Match: 'cat' -> animal (index=0) // Match: 'catalog' -> book (index=1) // Match: 'cat' -> animal (index=0) // Match: 'category' -> classification (index=2) // Match: 'cat' -> animal (index=0) ``` ### Response N/A (This is a method call, not an API response) ### Response Example N/A ``` -------------------------------- ### Parse Text - Find All Matches (Callback) Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Parses text using a callback interface for memory-efficient processing of matches. The IHit callback is invoked for each match, ideal for large texts or immediate match handling. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap map = new TreeMap<>(); map.put("Java", "programming language"); map.put("Python", "programming language"); map.put("code", "verb/noun"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); String text = "I love Java and Python code!"; // Use callback for memory-efficient processing acdat.parseText(text, new AhoCorasickDoubleArrayTrie.IHit() { @Override public void hit(int begin, int end, String value) { System.out.printf("Match: '%s' [%d:%d] -> %s%n", text.substring(begin, end), begin, end, value); } }); // Output: // Match: 'Java' [7:11] -> programming language // Match: 'Python' [16:22] -> programming language // Match: 'code' [23:27] -> verb/noun // Or use Java 8+ lambda syntax acdat.parseText(text, (begin, end, value) -> { System.out.printf("[%d:%d] = %s%n", begin, end, value); }); ``` -------------------------------- ### Parse Text with Callback Source: https://github.com/hankcs/ahocorasickdoublearraytrie/blob/master/README.md Process hits using a callback interface or lambda to avoid creating a large list of results. ```java acdat.parseText(text, new AhoCorasickDoubleArrayTrie.IHit() { @Override public void hit(int begin, int end, String value) { System.out.printf("[%d:%d]=%s\n", begin, end, value); } }); ``` ```java acdat.parseText(text, (begin, end, value) -> { System.out.printf("[%d:%d]=%s\n", begin, end, value); }); ``` -------------------------------- ### Serialization: save and load Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Persist the AhoCorasickDoubleArrayTrie to disk and restore it later. This is useful for avoiding the overhead of rebuilding the trie, especially when dealing with large dictionaries. ```APIDOC ## save and load - Serialization ### Description Persist the AhoCorasickDoubleArrayTrie to disk and restore it later. This avoids rebuilding the trie from scratch, which is useful when the dictionary is large and build time is significant. ### Method N/A (These are methods within the AhoCorasickDoubleArrayTrie class, not REST endpoints) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.io.*; import java.util.TreeMap; // Build a large trie TreeMap dictionary = new TreeMap<>(); dictionary.put("algorithm", "A step-by-step procedure"); dictionary.put("data", "Information processed by computer"); dictionary.put("structure", "Organization of data"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(dictionary); // Save to file using ObjectOutputStream String filePath = "/tmp/acdat.dat"; try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) { acdat.save(out); System.out.println("Trie saved successfully"); } // Load from file using ObjectInputStream AhoCorasickDoubleArrayTrie loadedAcdat = new AhoCorasickDoubleArrayTrie<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) { loadedAcdat.load(in); System.out.println("Trie loaded successfully"); } // Verify loaded trie works System.out.println(loadedAcdat.get("algorithm")); // Output: A step-by-step procedure // Alternative: Use Java serialization directly try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) { out.writeObject(acdat); } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) { AhoCorasickDoubleArrayTrie restored = (AhoCorasickDoubleArrayTrie) in.readObject(); System.out.println("Restored size: " + restored.size()); // Output: Restored size: 3 } ``` ### Response N/A (These are method calls, not API responses) ### Response Example N/A ``` -------------------------------- ### Check for pattern existence Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use matches to efficiently determine if any dictionary pattern exists within the provided text. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.HashMap; HashMap badWords = new HashMap<>(); badWords.put("spam", 1); badWords.put("scam", 2); badWords.put("phishing", 3); AhoCorasickDoubleArrayTrie filter = new AhoCorasickDoubleArrayTrie<>(); filter.build(badWords); // Check various texts System.out.println(filter.matches("This is a normal message")); // false System.out.println(filter.matches("This looks like spam")); // true System.out.println(filter.matches("Beware of phishing attempts")); // true System.out.println(filter.matches("")); // false ``` -------------------------------- ### Parse text with cancellation Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use IHitCancellable to stop the search process early once a specific number of matches is reached. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; import java.util.ArrayList; import java.util.List; TreeMap map = new TreeMap<>(); map.put("error", "ERROR"); map.put("warning", "WARNING"); map.put("info", "INFO"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); String logText = "info: starting... warning: low memory... error: crash... warning: retry"; // Find only the first 2 matches List firstTwoMatches = new ArrayList<>(); acdat.parseText(logText, new AhoCorasickDoubleArrayTrie.IHitCancellable() { @Override public boolean hit(int begin, int end, String value) { firstTwoMatches.add(value); return firstTwoMatches.size() < 2; // Stop after 2 matches } }); System.out.println("First 2 matches: " + firstTwoMatches); // Output: First 2 matches: [INFO, WARNING] ``` -------------------------------- ### Build Trie from Dictionary Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Constructs an AhoCorasickDoubleArrayTrie from a map of patterns to associated values. This is a one-time operation before text parsing. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; // Create dictionary mapping patterns to their associated values TreeMap dictionary = new TreeMap<>(); dictionary.put("hers", "pronoun"); dictionary.put("his", "pronoun"); dictionary.put("she", "pronoun"); dictionary.put("he", "pronoun"); dictionary.put("her", "pronoun"); // Build the trie (one-time operation) AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(dictionary); // The trie is now ready for parsing and is thread-safe System.out.println("Dictionary size: " + acdat.size()); // Output: Dictionary size: 5 ``` -------------------------------- ### Retrieve Dictionary Size with AhoCorasickDoubleArrayTrie Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Use the size method to count the number of keywords stored in the trie, which is useful for validation and statistics. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; // Build trie TreeMap map = new TreeMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(map); System.out.println("Dictionary contains " + acdat.size() + " keywords"); // Output: Dictionary contains 3 keywords // Empty trie AhoCorasickDoubleArrayTrie emptyTrie = new AhoCorasickDoubleArrayTrie<>(); emptyTrie.build(new TreeMap<>()); System.out.println("Empty trie size: " + emptyTrie.size()); // Output: Empty trie size: 0 ``` -------------------------------- ### Serialize and deserialize AhoCorasickDoubleArrayTrie Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Persists the trie to disk to avoid rebuilding from scratch. Supports both explicit save/load methods and standard Java object serialization. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.io.*; import java.util.TreeMap; // Build a large trie TreeMap dictionary = new TreeMap<>(); dictionary.put("algorithm", "A step-by-step procedure"); dictionary.put("data", "Information processed by computer"); dictionary.put("structure", "Organization of data"); AhoCorasickDoubleArrayTrie acdat = new AhoCorasickDoubleArrayTrie<>(); acdat.build(dictionary); // Save to file using ObjectOutputStream String filePath = "/tmp/acdat.dat"; try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) { acdat.save(out); System.out.println("Trie saved successfully"); } // Load from file using ObjectInputStream AhoCorasickDoubleArrayTrie loadedAcdat = new AhoCorasickDoubleArrayTrie<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) { loadedAcdat.load(in); System.out.println("Trie loaded successfully"); } // Verify loaded trie works System.out.println(loadedAcdat.get("algorithm")); // Output: A step-by-step procedure // Alternative: Use Java serialization directly try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) { out.writeObject(acdat); } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) { AhoCorasickDoubleArrayTrie restored = (AhoCorasickDoubleArrayTrie) in.readObject(); System.out.println("Restored size: " + restored.size()); // Output: Restored size: 3 } ``` -------------------------------- ### Update Value for Existing Key Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt This endpoint allows updating the value associated with an existing key in the AhoCorasickDoubleArrayTrie. It returns true if the key was found and updated, and false otherwise. New keys cannot be added after the trie has been built. ```APIDOC ## set - Update Value for Existing Key ### Description Update the value associated with an existing key. Returns true if the key exists and was updated, false otherwise. Note: You cannot add new keys after building; only existing keys can be updated. ### Method N/A (This is a method within the AhoCorasickDoubleArrayTrie class, not a REST endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap scores = new TreeMap<>(); scores.put("player1", 100); scores.put("player2", 150); AhoCorasickDoubleArrayTrie trie = new AhoCorasickDoubleArrayTrie<>(); trie.build(scores); // Update existing key boolean updated = trie.set("player1", 200); System.out.println("Updated: " + updated); // Output: Updated: true System.out.println("New score: " + trie.get("player1")); // Output: New score: 200 // Try to update non-existing key boolean failed = trie.set("player3", 50); System.out.println("Updated: " + failed); // Output: Updated: false ``` ### Response N/A (This is a method call, not an API response) ### Response Example N/A ``` -------------------------------- ### Update values in AhoCorasickDoubleArrayTrie Source: https://context7.com/hankcs/ahocorasickdoublearraytrie/llms.txt Updates the value for an existing key. Note that new keys cannot be added after the trie has been built. ```java import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import java.util.TreeMap; TreeMap scores = new TreeMap<>(); scores.put("player1", 100); scores.put("player2", 150); AhoCorasickDoubleArrayTrie trie = new AhoCorasickDoubleArrayTrie<>(); trie.build(scores); // Update existing key boolean updated = trie.set("player1", 200); System.out.println("Updated: " + updated); // Output: Updated: true System.out.println("New score: " + trie.get("player1")); // Output: New score: 200 // Try to update non-existing key boolean failed = trie.set("player3", 50); System.out.println("Updated: " + failed); // Output: Updated: false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.