问题在于......我不想使用多张地图,只需要一张地图。
我的目标是获取我在输入中输入的名称列表。 我尝试了一百个不同的for循环,但我总是倾向于最终得到整个地图的列表和/或覆盖重复的密钥。
import java.util.*;
public class Another {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name;
HashMap<String, ToA>wordkey = new HashMap<String, ToA>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", a);
wordkey.put("Dalton", b);
wordkey.put("James", c);
wordkey.put("Dalton", d);
System.out.println("Efternamn:");
name = scan.next();
}
}
public class ToA{
private String fname, lname, dob;
public ToA(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public String toString(){
return "\nFirstname: " + fname + "\nSurname: " + lname + "\nDateOfBirth: " + dob;
}
}
输入Dalton,我想要输出 名字:比尔 姓:道尔顿 DateOfBirth:18701005-2232
名字:Emmet 姓:道尔顿 DateOfBirth:18710713-0818
我真的坚持这一点,所以任何帮助都非常感谢,谢谢
答案 0 :(得分:3)
要发表评论作为答案:请使用Map<String, List<ToA>>
这样:
Map<String, List<ToA>> wordkey = new HashMap<>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", Arrays.asList(a));
wordkey.put("James", Arrays.asList(c));
wordkey.put("Dalton", Arrays.asList(b, d));
要根据输入打印名称,您可以执行以下操作:
System.out.println("Efternamn:");
name = scan.next();
List<ToA> toas = wordkey.get(name);
if (toas != null) {
System.out.println("ToAs");
for (ToA toa : toas) {
System.out.println("ToA: " + toa);
}
}
else {
System.out.println("No ToAs found for input: " + name);
}
答案 1 :(得分:1)