Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading