Created
May 24, 2021 14:06
-
-
Save ashutosh049/ea9a4e1e62ad5506209e7a2aba4a4b12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.Builder; | |
import lombok.Getter; | |
import lombok.Setter; | |
import lombok.ToString; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.stream.IntStream; | |
public class TestStreamCountOperation { | |
private static Consumer<List<QRCode>> printQrCodes = | |
qrCodeList_ -> qrCodeList_.forEach(qrCode_ -> System.out.println(qrCode_.toString())); | |
public static void main(String[] args) { | |
// | |
List<QRCode> qrCodeList = new ArrayList<>(); | |
IntStream.range(1, 5) | |
.forEach( | |
i -> { | |
qrCodeList.add(QRCode.builder().id(i).expiry(new Date()).build()); | |
}); | |
System.out.println("Before upate ::"); | |
printQrCodes.accept(qrCodeList); | |
long countQRCodes = | |
qrCodeList.stream() | |
.map( | |
qrCode_ -> { | |
qrCode_.setId(qrCode_.getId() * 2); | |
System.out.println("\t Operation Inside map"); | |
return qrCode_; | |
}) | |
.count(); | |
System.out.println("After update ::"); | |
printQrCodes.accept(qrCodeList); | |
} | |
} | |
@Getter | |
@Setter | |
@Builder | |
@ToString | |
class QRCode { | |
private int id; | |
private Date expiry; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fom official documentation java.util.stream.Stream#count
An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated. Behavioral parameters with side-effects, which are strongly discouraged except for harmless cases such as debugging, may be affected. For example, consider the following stream:
The number of elements covered by the stream source, a List, is known and the intermediate operation, peek, does not inject into or remove elements from the stream (as may be the case for flatMap or filter operations). Thus the count is the size of the List and there is no need to execute the pipeline and, as a side-effect, print out the list elements.