从对象的HashSet中检索值

时间:2015-01-26 20:42:26

标签: java hashset

嗨,大家好只是想要提高我的Java技能(忘了这么多)。 而对于我的生活,我不记得如何从HashSet对象打印出一个特定的元素。到目前为止,我已经创建了对象并将它们添加到HashSet

    Teacher teacher1 = new Teacher("Miss Marple", 63, "English");
    Teacher teacher2 = new Teacher("Mr White", 26, "Maths");
    Teacher teacher3 = new Teacher("Mrs Janet", 46, "Science");
    Teacher teacher4 = new Teacher("Mr Hancock", 35, "Art");
    Collection<Teacher> staff = new HashSet<Teacher>();
    staff.add(teacher1);
    staff.add(teacher2);
    staff.add(teacher3);
    staff.add(teacher4);

现在我如何检索和打印每个教师对象的名称变量?

由于

2 个答案:

答案 0 :(得分:1)

for (Teacher teacher : staff) {
  ...
}

如果你需要按插入顺序使用LinkedHashSet

答案 1 :(得分:0)

Java 8 使用流

staff.stream().forEach(x->System.out.println(x.name));