2 Ocak 2020 Perşembe

IntStream Yaratma

Giriş
Bu yazıdaki metodların hepsi Factory metodudur. IntSream nesnesini yaratir.

generate metodu
generate() ve iterate() birbirlerine benziyorlar ancak aralarında fark var. Açıklaması şöyle. Dolayısıyla paralel işlemlerde generate() kullanmak gerekir. Çünkü sıra önemli değildir. iterate() ise sıralı stream ürettiği için paralel işlemlerde kullanılmasa daha iyi.
- generate takes a IntSupplier, which means that you are supposed to generate ints without being given anything. Example usages include creating a constant stream of the same integer, creating a stream of random integers. Notice how each element in the stream do not depend on the previous element.


- iterate takes a seed and a IntUnaryOperator, which means that you are supposed to generate each element based on the previous element. This is useful for creating a inductively defined sequence, for example. In this case, each element is supposed to depend on the previous one.
iterate metodu - initial element + IntUnaryOperator
Örnek
limit() ile verilen değer kadar iterate edilir. Şöyle yaparız.
IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));
Aynı şeyi şöyle de yapabiliriz. Ancak bu yöntem i değerini değiştirdiği için makbul değil.
IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);
iterate metodu - initial element + IntPredicate has next + IntUnaryOperator next element
Java 9 ile geliyor. Açıklaması şöyle.
first parameter - the initial element;
second parameter - a predicate to apply to elements to determine when the stream must terminate;
third parameter- a function to be applied to the previous element to produce a new element.
Şöyle yaparız. Üçüncü parametre bir önceki iterasyonda kabul edilen değerdir.
int[] seq = IntStream.iterate(0, x -> ..., x -> ...).toArray();
of metodu - int []
Şöyle yaparız.
int[] itemsInStock =  ...;

IntSummaryStatistics stat = IntStream.of(itemsInStock).summaryStatistics();
range metodu
Sıralı bir stream döndürür
Örnek
Elimizde şöyle bir kod olsun
System.out.println("#1");
Stream.of(0, 1, 2, 3)
        .peek(e -> System.out.println(e))
        .sorted()
        .findFirst();

System.out.println("\n#2");
IntStream.range(0, 4)
        .peek(e -> System.out.println(e))
        .sorted()
        .findFirst();
Çıktı olarak şunu alırız
#1
0
1
2
3

#2
0
Açıklaması şöyle
Well, IntStream.range() returns a sequential ordered IntStream from startInclusive(inclusive) to endExclusive (exclusive) by an incremental step of 1, which means it's already sorted. Since it's already sorted, it makes sense that the following .sorted() intermediate operation does nothing. As a result, peek() is executed on just the first element (since the terminal operation only requires the first element).

On the other hand, the elements passed to Stream.of() are not necessarily sorted (and the of() method doesn't check if they are sorted). Therefore, .sorted() must traverse all the elements in order to produce a sorted stream, which allows the findFirst() terminal operation to return the first element of the sorted stream. As a result, peek is executed on all the elements, even though the terminal operation only needs the first element.
Örnek - start + end
Primitive array'den yaratmak için şöyle yaparız.
DoubleStream ds = IntStream.range(0, floatArray.length)
                           .mapToDouble(i -> floatArray[i]);
Örnek - start + end
Şöyle yaparız.  0 ile 10 arasındaki sayıların toplamını bulur. Reduce ile range() ile elde edilen her yeni eleman add işlemine sokularak toplama eklenir. reduce işlemi 0'dan başlar.
IntBinaryOperator add = (a, b) -> a + b;
int sum2 = IntStream.range(0, 10)
                    .reduce(0, add);
Örnek - start + end
Bir başka örnekte elimizde bir items listesi var. Bu listedeki her elemanı bulunduğu indekse göre bir Map<Integer,Item> veri yapısına doldurmak istiyoruz. range ile 0-size() arasında sayı üretiriz. Bu sayı Integer nesnesine çevrilir. Daha sonra collect() metodu ile Map'e çevrilir.
Map<Integer,Item> map = 
    IntStream.range(0,items.size())
             .boxed()
             .collect(Collectors.toMap (i -> i, i -> items.get(i)));

rangeClosed metodu - start + end
Örnek
Şöyle yaparız.
IntStream.rangeClosed('A', 'Z')
  .mapToObj(a -> (char) a)
  .collect(...)
  .forEach(System.out::print); 

Hiç yorum yok:

Yorum Gönder