1. import java.io.*;
  2. import java.util.*;
  3. public class DataIndexer {
  4. private static final String CONFIG_FILE = "config.txt";
  5. private static final String INDEX_FILE = "index.txt";
  6. private Map<String, List<String>> index = new HashMap<>();
  7. public DataIndexer() {
  8. loadConfiguration();
  9. buildIndex();
  10. }
  11. // Loads the configuration from config.txt
  12. private void loadConfiguration() {
  13. try (BufferedReader reader = new BufferedReader(new FileReader(CONFIG_FILE))) {
  14. String line;
  15. while ((line = reader.readLine()) != null) {
  16. String[] parts = line.split(",");
  17. if (parts.length == 2) {
  18. index.put(parts[0].trim(), Arrays.asList(parts[1].trim().split(" ")));
  19. }
  20. }
  21. } catch (IOException e) {
  22. System.err.println("Error loading configuration: " + e.getMessage());
  23. }
  24. }
  25. // Builds the index based on the configuration
  26. private void buildIndex() {
  27. // In a real application, this would read the user data.
  28. // For this example, we'll simulate data loading.
  29. List<String> data = simulateUserData();
  30. for (String item : data) {
  31. for (Map.Entry<String, List<String>> entry : index.entrySet()) {
  32. if (entry.getKey().contains(item)) { //add if contains
  33. entry.getValue().add(item);
  34. }
  35. }
  36. }
  37. // Write the index to index.txt
  38. try (BufferedWriter writer = new BufferedWriter(new FileWriter(INDEX_FILE))) {
  39. for (Map.Entry<String, List<String>> entry : index.entrySet()) {
  40. writer.write(entry.getKey() + ":" + entry.getValue().toString());
  41. writer.newLine();
  42. }
  43. } catch (IOException e) {
  44. System.err.println("Error writing index: " + e.getMessage());
  45. }
  46. }
  47. private List<String> simulateUserData() {
  48. return Arrays.asList("apple", "banana", "orange", "grapefruit", "apple pie");
  49. }
  50. // Searches the index for a given term
  51. public List<String> search(String term) {
  52. List<String> results = new ArrayList<>();
  53. for (Map.Entry<String, List<String>> entry : index.entrySet()) {
  54. if (entry.getKey().contains(term)) {
  55. results.addAll(entry.getValue());
  56. }
  57. }
  58. return results;
  59. }
  60. public static void main(String[] args) {
  61. DataIndexer indexer = new DataIndexer();
  62. //Example usage
  63. List<String> searchResults = indexer.search("apple");
  64. System.out.println("Search results for 'apple': " + searchResults);
  65. }
  66. }

Add your comment