Video tayyorlanmoqda

reduce() qanday ishlaydi va identity qiymati nima uchun kerak?

reduce elementlarni bitta natijaga yig'adi: identity'dan boshlaydi va har bir elementni accumulator bilan oldingi natijaga qo'shadi. Identity — bo'sh stream'da qaytadigan va natijani buzmaydigan boshlang'ich qiymat.

📖 Javob

List<Integer> nums = List.of(3, 5, 7);

int sum = nums.stream().reduce(0, Integer::sum);          // 15
int product = nums.stream().reduce(1, (a, b) -> a * b);   // 105
Optional<Integer> max = nums.stream().reduce(Integer::max); // Optional[7]

Uch xil variant bor:

  • reduce(identity, accumulator) — natija har doim bor, bo'sh stream'da identity;
  • reduce(accumulator) — identity yo'q, shuning uchun Optional qaytaradi;
  • reduce(identity, accumulator, combiner) — natija turi element turidan farq qilsa yoki parallel stream uchun.

Identity tanlashdagi xato:

int sum = nums.stream().reduce(10, Integer::sum);

Ketma-ket stream'da 25 chiqadi, parallel'da esa 10 har bir bo'lakka qo'shilib, boshqa son chiqishi mumkin. Identity'ning sharti: identity op x == x. Qo'shish uchun 0, ko'paytirish uchun 1.

Amalda yig'indi uchun mapToInt(...).sum(), eng kattasi uchun max(...), satr uchun joining o'qishga osonroq. reduce ni ular yetmaganda ishlating.