View Javadoc
1   /*
2   UnnecessaryNullCheckWithInstanceOf
3   
4   */
5   
6   package com.puppycrawl.tools.checkstyle.checks.coding.unnecessarynullcheckwithinstanceof;
7   
8   import java.util.List;
9   import java.util.ArrayList;
10  import java.util.Objects;
11  import java.util.function.Predicate;
12  
13  public class InputUnnecessaryNullCheckWithInstanceOfLambda {
14      private final List<Object> objects = new ArrayList<>();
15      public void simpleLambdas() {
16          objects.forEach(obj -> {
17              if (obj != null && obj instanceof String) { // violation, 'Unnecessary nullity check'
18                  String str = (String) obj;
19              }
20          });
21  
22          // violation below, 'Unnecessary nullity check'
23          Predicate<Object> isString = obj -> obj != null && obj instanceof String;
24  
25          // violation below, 'Unnecessary nullity check'
26          objects.removeIf(obj -> obj != null && obj instanceof Integer);
27      }
28      public void validLambdas() {
29          objects.forEach(obj -> {
30              if (obj instanceof String) {
31                  String str = (String) obj;
32              }
33          });
34          objects.stream()
35                 .filter(Objects::nonNull)
36                 .filter(obj -> obj instanceof String)
37                 .forEach(obj -> {
38                     String str = (String) obj;
39                 });
40      }
41  }