Video tayyorlanmoqda

anyMatch, allMatch va noneMatch bo'sh stream'da nima qaytaradi?

Bo'sh stream'da anyMatch — false, allMatch — true, noneMatch — true qaytaradi. Mantiqan: "biror element shartga mos keladimi" — yo'q; "hammasi mosmi" — rad etadigan element yo'q, demak ha.

📖 Javob

List<Integer> empty = List.of();

empty.stream().anyMatch(x -> x > 0);   // false
empty.stream().allMatch(x -> x > 0);   // true
empty.stream().noneMatch(x -> x > 0);  // true

allMatch'ning true qaytarishi ko'pchilikni hayron qoldiradi va prodda bug bo'ladi:

// "barcha to'lovlar tasdiqlanganmi?"
boolean allPaid = order.payments().stream().allMatch(Payment::confirmed);
if (allPaid) ship(order);   // to'lov umuman yo'q bo'lsa ham jo'natib yuboradi!

To'g'risi — bo'shlikni alohida tekshirish:

boolean ready = !order.payments().isEmpty()
        && order.payments().stream().allMatch(Payment::confirmed);

Uchala metod ham short-circuit: javob aniq bo'lishi bilan to'xtaydi. anyMatch birinchi mos elementda, allMatch birinchi mos kelmaganda tugaydi — qolgan elementlar tekshirilmaydi.