我有一个Dictionary<int BossID, string BossName> ListOfBosses
和Dictionary<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/