Junior — Middle
How can an efficient data structure for fast data lookup in a table be implemented?
sobes.tech AI
Answer from AI
To quickly search for data in a table in Java, you can use data structures that provide efficient key-based access, such as:
- HashMap. Allows for search, insertion, and deletion in amortized O(1) time.
- TreeMap. Maintains sorted keys and provides operations in O(log n).
Example of using HashMap for quick search:
import java.util.HashMap;
public class FastSearch {
public static void main(String[] args) {
HashMap<Integer, String> dataMap = new HashMap<>();
dataMap.put(1, "Apple");
dataMap.put(2, "Banana");
dataMap.put(3, "Cherry");
// Quick search by key
String value = dataMap.get(2); // "Banana"
System.out.println(value);
}
}
If the data requires searching by multiple fields or complex conditions, you can use additional indexes or specialized structures, such as Trie, B-trees, or databases with index support.