6 Ocak 2020 Pazartesi

Stream.count metodu

Giriş
Açıklaması şöyle
The Stream::count terminal operation counts the number of elements in a Stream. The complexity of the operation is often O(N), meaning that the number of sub-operations is proportional to the number of elements in the Stream.
Bir diğer açıklama şöyle.
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:
Örnek
Elimizde şöyle bir kod olsun. Bu kod map() çağrısını işletmez çünkü count() metodu sonucu önceden biliyordur.
StringBuilder sb = new StringBuilder();

var count = Stream.of(new String[]{"1", "2", "3", "4"})
  .map(sb::append)
  .count();

System.out.println(count); //4
System.out.println(sb.toString()); //""
Ancak kodu şöyle yaparsak, bu sefer farklı sonuç alırız.
var count = Stream.of(new String[]{"1", "2", "3", "4"})
 .filter(s -> true)
 .map(sb::append)
 .count();

System.out.println(count); //4
System.out.println(sb.toString()); //1234

Hiç yorum yok:

Yorum Gönder