-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
  • 118,400
  • 24
  • 176
  • 257

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
  • 41,524
  • 11
  • 90
  • 115
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,211
  • 5
  • 28
  • 59