如何显示LinkedHashMap值

时间:2015-05-18 10:12:40

标签: java dictionary linkedhashmap

我遇到了使用LinkedHashMap迭代并显示值的问题。 我有一个Model类,它具有属性的getter setter。

这是我的主要班级......

public class main {

public static void main(String[] args) throws SQLException {

    DemoHandler handler = new DemoHandler();
    LinkedHashMap<String, Model> hashMap = new LinkedHashMap<String, Model>();
    Model modelInfo = new Model();

    modelInfo.setId(1);
    modelInfo.setName("Subho");
    modelInfo.setEmail("sm@gammainfotech.com");
    modelInfo.setAge("24");
    modelInfo.setGender("Male");
    hashMap.put("100", modelInfo);
    System.out.println(modelInfo.getName());// It shows Subho, which is fine

    modelInfo.setId(2);
    modelInfo.setName("Diba");
    modelInfo.setEmail("sm@gammainfotech.com");
    modelInfo.setAge("25");
    modelInfo.setGender("Male");
    hashMap.put("101", modelInfo);
    System.out.println(modelInfo.getName());// It shows Diba, which is fine

    modelInfo.setId(3);
    modelInfo.setName("Jeet");
    modelInfo.setEmail("sm@gammainfotech.com");
    modelInfo.setAge("28");
    modelInfo.setGender("Male");
    hashMap.put("102", modelInfo);
    System.out.println(modelInfo.getName());// It shows Jeet, which is fine

    for (Map.Entry<String, Model> entry : hashMap.entrySet()) {
            Model m = entry.getValue();                
            System.out.println(m.getName());// Here I can see only Jeet thrice. The iterator iterates 3 times which is fine but the value it gives only the last data I entry. It should shows Subho,Diba,Jeet here.
    }

 }
}  

现在,当我运行时,输出显示......

Subho 迪吧 截拳道

截拳道 截拳道 截拳道

请帮我展示所有价值观。

2 个答案:

答案 0 :(得分:2)

您正在向Map多次添加相同的Model实例,因此每次使用新添加的Model的属性覆盖先前添加的Model的属性。

您应该向Map添加唯一的Model实例:

Model modelInfo = new Model();

modelInfo.setId(1);
modelInfo.setName("Subho");
modelInfo.setEmail("sm@gammainfotech.com");
modelInfo.setAge("24");
modelInfo.setGender("Male");
hashMap.put("100", modelInfo);
System.out.println(modelInfo.getName());// It shows Subho, which is fine

modelInfo = new Model();
modelInfo.setId(2);
modelInfo.setName("Diba");
modelInfo.setEmail("sm@gammainfotech.com");
modelInfo.setAge("25");
modelInfo.setGender("Male");
hashMap.put("101", modelInfo);
System.out.println(modelInfo.getName());// It shows Diba, which is fine

modelInfo = new Model();
modelInfo.setId(3);
modelInfo.setName("Jeet");
modelInfo.setEmail("sm@gammainfotech.com");
modelInfo.setAge("28");
modelInfo.setGender("Male");
hashMap.put("102", modelInfo);

答案 1 :(得分:1)

感谢Eran的回答,你解决了问题。

现在,我建议您使用优雅的新方法使用java 8功能输出LinkedHashMap(Lambdas ...)

这是旧方式:

for (Map.Entry<String, Model> entry : hashMap.entrySet()) {
           Model m = entry.getValue();                
           System.out.println(m.getName());
}

这是新的方式

hashMap.forEach((s, m) -> System.out.println(m.getName()));