-2

I have created several objects and I want to print only one parameter of the objects in 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);

I want to print:

Bruce
Rachel
Tony
Pepper
Pshemo
  • 122,468
  • 25
  • 185
  • 269

2 Answers2

2

Before Java 8

for (Human human : people) {
    System.out.println(human.getName());
}

Starting from Java 8

people.stream().map(Human::getName).forEach(System.out::println);
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1
for(Human human : people) {
    System.out.println(human.getName());
}

This should print name for each human in people list. You should have method in Human class:

getName() {
    return this.name;
}
ByeBye
  • 6,650
  • 5
  • 30
  • 63