java - 将 ID 列表与其对应的对象进行匹配

标签 java dictionary arraylist

我有一个Dictionary<int BossID, string BossName> ListOfBossesDictionary<String EmpName, int BossID> ListOfEmps 。当然,将 BossID 与 Boss 匹配并返回 'Dictionary WhoIsMyBoss'。

我不知道从哪里开始学习 Java。

就这两个列表而言,我们假设 Boss 与 Emps 之间存在一对多的比例。并且BossID是从1-n递增的。

我想我会在我不识字的 Java 中执行以下操作。 。 .

Dictionary<BossName, EmpName> WhoIsMyBoss;
ArrayList<Integer> AnotherListOfBosses;
private int Boss;
for (String EmpName: ListOfEmps)
        Boss = ListOfEmps.get(EmpName)
        WhoIsMyBoss.put(ListofBosses(Boss) , EmpName);
        AnotherListOfBosses.add(Boss);
}
for(int Boss: AnotherListOfBosses)
{
     ListOfBosses.remove(Boss)
}

这应该给我留下一份老板和员工的名单以及一份 希望没有相应员工的 ListOfBosses。

看起来怎么样? Dictionary 是正确使用的 Collection 吗?如有任何改进,我们将不胜感激。

最佳答案

正如 Kilian Foth 提到的,您应该使用 Map 而不是 Dictionary。此外,在 Java 中,约定变量名以小写字母开头,类名以大写字母开头。

您说过名称是字符串,ID 是整数。

public class BossExample {
  // Key: Boss-ID, Value: Boss name
  private Map<Integer, String> mapOfBosses = new HashMap<Integer, String>();

  // Key: Emp name, Value: Boss-ID
  private Map<String, Integer> mapOfEmps = new HashMap<String, Integer>();

  // Constructor fills the maps
  public BossExample() {
    // ...
  }

  // Returns a mapping from Emp name to Boss name
  public Map<String, String> getEmpToBossMap() {
    final Map<String, String> empToBossMap = new HashMap<String, String>();

    // Iterate through mapOfEmps via entrySet giving you key and value 
    // at the same time
    for(Map.Entry<String, Integer> empEntry : mapOfEmps.entrySet()) {
      // Put the Emp name as key and the retrieved Boss name as a value into 
      // the result map.
      empToBossMap.put(empEntry.getKey(), mapOfBosses.get(empEntry.getValue()));
    }

    return empToBossMap;
  }
}

关于java - 将 ID 列表与其对应的对象进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562213/

相关文章:

java - 没有可用于处理的 EJB 接收器

java - Integer.parseInt 返回错误 : The method parseInt(String) in the type Integer is not applicable for the arguments (R. 字符串)

java - 我应该如何设置 Firebase 实时数据库中键值类型的 getter 和 setter?

javascript - JavaScript 中的嵌套哈希表

c++ - 值类型在map中的地址

google-maps - 自昨晚以来,Google map 信息窗口变小

java - 在 Android 中保存 ArrayList 的最简单方法是什么?

java - 通过 ArrayList 的反向迭代给出 IndexOutOfBoundsException

java - 带有 maven 和无法解析的构建扩展的 Android : Plugin com. jayway.maven.plugins.android.generation2 :android-maven-plugin:3. 9.0-rc.3

java - 如何获取 C[] 的类对象,给定 C 的类对象