-2

I need to iterate over Objects and add every elements name to ArrayList. My class Command contains getName() method.

  • commands = List< Command >

I've done it without streams.

     ArrayList<String> commandList = new ArrayList<String>(); for
     (Command currentCommand : commands.getCommands()) {
     commandList.add(currentCommand.getName()); }

Here's what I've got now:

commands.getCommands().forEach(command -> { command.getName(); });

I want to do it in one line using streams

Naman
  • 27,789
  • 26
  • 218
  • 353
Piotr Szczepanik
  • 361
  • 2
  • 4
  • 17

1 Answers1

4

Try this

commands.getCommands().stream().map(Command::getName).collect(toList()); 
Hadi J
  • 16,989
  • 4
  • 36
  • 62