Search code examples
javacollectionshashmapjava-stream

stream.count() resulting in NPE


I am seeing some weird behaviour in Java stream API. Here's my code:

public static void main( String[] args ) {
    final List<String> list = Arrays.asList( "string1", "string2" );
    final Map<String, List<String>> map = new HashMap<>();
    map.put( "string1", Arrays.asList( "1" ) );
    //map.put( "string2", Arrays.asList( "1" ) );
    Stream<String> stream = list.stream().map( map::get ).flatMap( List::stream );
    System.out.println( "Stream=" + stream );
    long count = stream.count();
    System.out.println( "Stream count=" + count );
}

The second last line (long count = stream.count();) is resulting in a NPE. The exception does not occur if I add another entry to map for key "string2" (commented code). Can somebody please point-out why it results in a NPE instead of just returning the count as 1?

The same behaviour is observed if I try to collect the stream's result in a list instead of calling count()


Solution

  • Your code will call List#stream on null in the flatMap, which results in a NullPointerException. You need to filter out null values before the flatMap:

    list.stream()
            .map(map::get)
            .filter(Objects::nonNull)
            .flatMap(List::stream)