You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何按Key存储多行多值并实现指定值查询?

Java Implementation for Key + 5-Element Lookup to Get 6th Value

Got it, let's walk through a solid, efficient solution tailored to your requirements. The core goal is to build a nested lookup structure that lets you quickly map a top-level key, plus the first 5 elements of a line, to the corresponding 6th value.

1. Storage Structure Selection

Since your top-level key count is under 10000 (totally manageable), we’ll use a nested HashMap:

  • Outer Map<String, ...>: Maps your top-level key (like "ABC") to an inner map.
  • Inner Map<CompositeKey, String>: Maps the first 5 elements of a line directly to the 6th value.

Using a custom CompositeKey class (instead of a list or concatenated string) is the most reliable choice here—it avoids delimiter collision issues and ensures proper equality/hash code behavior for HashMap compatibility.

2. Custom Immutable CompositeKey Class

First, create an immutable class to represent the 5-element combination. Immutability is critical here to prevent broken lookups if key values change after insertion:

import java.util.Objects;

public class CompositeKey {
    private final String elem1;
    private final String elem2;
    private final String elem3;
    private final String elem4;
    private final String elem5;

    public CompositeKey(String elem1, String elem2, String elem3, String elem4, String elem5) {
        this.elem1 = elem1;
        this.elem2 = elem2;
        this.elem3 = elem3;
        this.elem4 = elem4;
        this.elem5 = elem5;
    }

    // Override equals and hashCode for proper HashMap functionality
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CompositeKey that = (CompositeKey) o;
        return Objects.equals(elem1, that.elem1) &&
               Objects.equals(elem2, that.elem2) &&
               Objects.equals(elem3, that.elem3) &&
               Objects.equals(elem4, that.elem4) &&
               Objects.equals(elem5, that.elem5);
    }

    @Override
    public int hashCode() {
        return Objects.hash(elem1, elem2, elem3, elem4, elem5);
    }
}

3. Build the Data Store from File

Next, implement code to read your file, parse lines, and populate the nested map. We’ll use BufferedReader for efficient file reading. Note: This example assumes your file groups lines by top-level key (e.g., a line with just "ABC" starts a group, followed by its data lines). Adjust the parsing logic if your file format differs (e.g., top key is the first element of each data line):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DataLookupService {
    private final Map<String, Map<CompositeKey, String>> dataStore = new HashMap<>();

    // Load data from the target file
    public void loadData(String filePath) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String currentTopKey = null;
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue; // Skip empty lines

                // Check if line is a top-level key (no commas)
                if (!line.contains(",")) {
                    currentTopKey = line;
                    // Initialize inner map if it doesn't exist for this key
                    dataStore.putIfAbsent(currentTopKey, new HashMap<>());
                } else {
                    if (currentTopKey == null) {
                        System.err.println("Skipping data line without a preceding top key: " + line);
                        continue;
                    }

                    String[] elements = line.split(",");
                    if (elements.length != 6) {
                        System.err.println("Skipping invalid data line (needs 6 elements): " + line);
                        continue;
                    }

                    CompositeKey compositeKey = new CompositeKey(
                        elements[0], elements[1], elements[2], elements[3], elements[4]
                    );
                    String sixthValue = elements[5];

                    // Overwrite existing value if duplicate key exists (adjust if you need to store multiple values)
                    dataStore.get(currentTopKey).put(compositeKey, sixthValue);
                }
            }
        }
    }

    // Lookup method: Retrieve 6th value by top key + first 5 elements
    public String lookup(String topKey, String elem1, String elem2, String elem3, String elem4, String elem5) {
        Map<CompositeKey, String> innerMap = dataStore.get(topKey);
        if (innerMap == null) {
            return null; // Or throw a custom exception if preferred
        }
        CompositeKey compositeKey = new CompositeKey(elem1, elem2, elem3, elem4, elem5);
        return innerMap.get(compositeKey);
    }
}

4. Usage Example

Here’s how you’d integrate this service into your application:

public class Main {
    public static void main(String[] args) {
        DataLookupService lookupService = new DataLookupService();
        try {
            lookupService.loadData("your-data-file.txt");
            
            // Example lookup: Key "ABC" with elements A,B,C,D,E
            String result = lookupService.lookup("ABC", "A", "B", "C", "D", "E");
            System.out.println("Found value: " + result); // Should print "123"
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. Key Considerations

  • Duplicate Entries: The current code overwrites the 6th value if the same top key + 5-element combination appears multiple times. If you need to store all matching values, change the inner map to Map<CompositeKey, List<String>>.
  • Performance: With <10000 top keys and HashMap’s average O(1) lookup time, this solution will perform extremely fast even with millions of data lines.
  • Error Handling: The example includes basic error handling for invalid lines—extend this with logging or custom exceptions based on your application’s needs.

内容的提问来源于stack exchange,提问作者utkarsh mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:53:41