我创建了几个对象,我想在ArrayList中只打印一个对象参数:
Superhero batman = new Superhero("Bruce", 26, "Batman");
Human rachel = new Human("Rachel", 24);
Superhero ironman = new Superhero("Tony", 35, "Ironman");
Human pepper = new Human("Pepper", 22);
List<Human> people = new ArrayList<Human>();
people.add(batman);
people.add(rachel);
people.add(ironman);
people.add(pepper);
我想打印:
Bruce
Rachel
Tony
Pepper
答案 0 :(得分:2)
在Java 8之前
for (Human human : people) {
System.out.println(human.getName());
}
从Java 8开始
people.stream().map(Human::getName).forEach(System.out::println);
答案 1 :(得分:0)
for(Human human : people) {
System.out.println(human.getName());
}
这应该为人员列表中的每个人打印名称。你应该在Human class中有方法:
getName() {
return this.name;
}