3

I have a list containing different commands all implemented the same interface (ICommand). These commands are each classes containing information on what the spesific command should do.

I want to be able to tell if the list contains two spesific commands, and do something if they appear together.

For example:

List<ICommand> commandList = getCommandList(); // not important how the list is made

pseudo code comming up:

if ( commandList contains HelpCommand.class && WriteHelpToFileCommand.class )

then do something (write the help to a file)

else do something else (print the help to console)

Can someone point me in the right direction?

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
Mr.Turtle
  • 2,600
  • 6
  • 23
  • 41

2 Answers2

2

Use the 'instanceof' operator to check if your list element is of class HelpCommand and/or WriteHelpToFileCommand.

It's well described here

Mr.Turtle
  • 2,600
  • 6
  • 23
  • 41
Guillaume Georges
  • 3,718
  • 3
  • 12
  • 30
  • I would like to check this without looping through the whole list. In that case I would have to loop through the list twice: first time to check whether the list contains the commands, and the other time to actually run the commands. – Mr.Turtle Sep 05 '17 at 14:41
2

You can use the stream API to check for this.

if(commandList.stream().anyMatch(e -> HelpCommand.class.isInstance(e)) && commandList.stream().anyMatch(e -> WriteHelpToFileCommand.class.isInstance(e))) {
    // do something
}
Jokab
  • 2,919
  • 1
  • 14
  • 25
  • 1
    I ended up doing something entirely different by changing some of the system design. The Java 8 streams was a perfect match. Thanks! – Mr.Turtle Sep 06 '17 at 14:43