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
  • 274,122
  • 60
  • 696
  • 724
Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46

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,950
  • 6
  • 28
  • 46
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
  • 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,939
  • 1
  • 15
  • 26
  • 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