-
-
Save ashutosh049/ea9a4e1e62ad5506209e7a2aba4a4b12 to your computer and use it in GitHub Desktop.
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; | |
} |
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:
List<String> l = Arrays.asList("A", "B", "C", "D");
long count = l.stream().peek(System.out::println).count();
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.
Output
Before upate ::
QRCode(id=1, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=2, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=3, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=4, expiry=Mon May 24 19:33:43 IST 2021)
Disconnected from the target VM, address: '127.0.0.1:60448', transport: 'socket'
After update ::
QRCode(id=1, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=2, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=3, expiry=Mon May 24 19:33:43 IST 2021)
QRCode(id=4, expiry=Mon May 24 19:33:43 IST 2021)
Process finished with exit code 0