Java 8 Stream cannot be reused, once its consumed or used. If you are trying to access the stream which already used or consumed will throw IllegalStateException
FilterNullValue.java
Output
Exception
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
at java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:94)
at java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:618)
at java.util.stream.ReferencePipeline$2.<init>(ReferencePipeline.java:163)
at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
at com.javatutorialcorner.java8.FilterNullValue.main(FilterNullValue.java:21)
package com.javatutorialcorner.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FilterNullValue { public static void main(String[] args) { StreamtopFootballPlayers = Stream.of("LIONEL MESSI", "CRISTIANO RONALDO", "LUIS SUAREZ", null, "NEYMAR", null, "SERGIO AGUERO", "MANUEL NEUER", "GARETH BALE", null, "ARJEN ROBBEN", "ANDRES INIESTA", "ZLATAN IBRAHIMOVIC"); List result = topFootballPlayers.collect(Collectors.toList()); System.out.println("Java 8 Convert a Stream to List"); result.forEach(System.out::println); System.out.println("Result after null values filtered "); List resultAfterNullFilter = topFootballPlayers.filter(x -> x!=null).collect(Collectors.toList()); } }
Output
Java 8 Convert a Stream to List
LIONEL MESSI
CRISTIANO RONALDO
LUIS SUAREZ
null
NEYMAR
null
SERGIO AGUERO
MANUEL NEUER
GARETH BALE
null
ARJEN ROBBEN
ANDRES INIESTA
ZLATAN IBRAHIMOVIC
Result after null values filtered
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
at java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:94)
at java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:618)
at java.util.stream.ReferencePipeline$2.<init>(ReferencePipeline.java:163)
at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
at com.javatutorialcorner.java8.FilterNullValue.main(FilterNullValue.java:22)
0 comments:
Post a Comment