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

如何通过LinkedHashMap中自定义ObjClass的字段获取对应Key?

Let's tackle this problem step by step—retrieving a key from a LinkedHashMap<Integer, ObjClass> by matching the name field of your custom class is totally doable, and I'll help you spot where things might be going wrong.

Step 1: Verify Your ObjClass Implementation

First, make sure your class follows JavaBean conventions for getters (this is a super common source of bugs). Here's a correct implementation that aligns with your description:

public class ObjClass {
    // Private fields (note: Java uses camelCase for field names, adjust if you used Name instead)
    private String name;
    private int level;
    private String parent;

    // Constructor (optional but useful for quick object initialization)
    public ObjClass(String name, int level, String parent) {
        this.name = name;
        this.level = level;
        this.parent = parent;
    }

    // Getters and Setters (critical for accessing private fields)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String getParent() {
        return parent;
    }

    public void setParent(String parent) {
        this.parent = parent;
    }
}

Double-check that your getter for the name field is exactly getName()—typos like getname() or get_Name() will break field access entirely.

Step 2: Correct Ways to Retrieve the Key

Since LinkedHashMap preserves insertion order, you can iterate through its key-value pairs to match the name field. Below are two reliable approaches:

Approach 1: Iterate with EntrySet (Java 7+)

This is a straightforward, readable way to loop through entries:

public static Integer getKeyByName(LinkedHashMap<Integer, ObjClass> map, String targetName) {
    for (Map.Entry<Integer, ObjClass> entry : map.entrySet()) {
        // Handle nulls to avoid NullPointerException
        if (targetName != null && targetName.equals(entry.getValue().getName())) {
            return entry.getKey(); // Returns first matching key (follows insertion order)
        }
        // Use this instead if you need case-insensitive matching:
        // if (targetName != null && targetName.equalsIgnoreCase(entry.getValue().getName())) {
        //     return entry.getKey();
        // }
    }
    return null; // Return null if no match found (or throw an exception if preferred)
}

Approach 2: Use Streams (Java 8+)

For a more concise, functional-style approach:

import java.util.stream.Collectors;
import java.util.List;

public static Integer getKeyByNameStream(LinkedHashMap<Integer, ObjClass> map, String targetName) {
    return map.entrySet()
            .stream()
            .filter(entry -> targetName != null && targetName.equals(entry.getValue().getName()))
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null); // Replace with orElseThrow() to throw an exception on no match
}

// If you need all keys matching the name (not just the first):
public static List<Integer> getAllMatchingKeys(LinkedHashMap<Integer, ObjClass> map, String targetName) {
    return map.entrySet()
            .stream()
            .filter(entry -> targetName != null && targetName.equals(entry.getValue().getName()))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

Step 3: Common Pitfalls to Troubleshoot

If your code still isn't working, check these common issues:

  • Null Pointer Exceptions: Ensure none of your ObjClass entries in the map are null, and that the name field isn't null (add null checks as shown above).
  • Case Sensitivity: If you're expecting a case-insensitive match (e.g., "alice" should match "Alice"), use equalsIgnoreCase() instead of equals().
  • Duplicate Names: If multiple entries have the same name, the methods above return the first one (thanks to LinkedHashMap's insertion order). Use the getAllMatchingKeys method if you need all matches.
  • Incorrect Field Name: If you named your field Name (uppercase N), adjust the getter to getName() (still follows JavaBean conventions) or rename the field to name for consistency.

Example Usage

Here's how to test these methods in action:

import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<Integer, ObjClass> objMap = new LinkedHashMap<>();
        objMap.put(1, new ObjClass("Alice", 2, "Parent1"));
        objMap.put(2, new ObjClass("Bob", 3, "Parent2"));
        objMap.put(3, new ObjClass("Alice", 1, "Parent3"));

        // Get first key matching "Alice"
        Integer singleKey = getKeyByName(objMap, "Alice");
        System.out.println("First matching key: " + singleKey); // Output: 1

        // Get all keys matching "Alice"
        List<Integer> allKeys = getAllMatchingKeys(objMap, "Alice");
        System.out.println("All matching keys: " + allKeys); // Output: [1, 3]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:53:56