Optional
في هذه الصفحة 8 موضوعات
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
نظرة عامة
الموضوعات
- إنشاء Optional
- التحويلات
- الاستخدام المناسب
تعلّم أولًا
46 دقيقة قراءة · 1.5 ساعة تدريب (تقدير)
مخرجات التعلم
- Return
Optionalfrom a method that may not find a result. - Transform and unwrap with
map,filter,orElse,orElseGet,orElseThrow. - State where
Optionalshould not be used (fields, parameters, collections).
الدروس
المختبر والتمارين
Lab
BEG-037-LAB1 · Safe lookups
Outcomes: 1–3 · Time: ~1 h Change findById in the generic repository (BEG-031) to return Optional and update all callers. Acceptance: no .get() without a check.
Exercises (assessment: three exercises)
| ID | Outcome | Task |
|---|---|---|
| BEG-037-EX01 | 1 | Write Optional<String> firstLongWord(List<String> words, int min) that returns the first word with at least min letters. |
| BEG-037-EX02 | 2 | Given Optional<String> name, print it upper-cased or "guest", and write a second version that throws IllegalStateException("name missing"). |
| BEG-037-EX03 | 3 | Fix these: a class with an Optional<String> field, a method with an Optional<Integer> parameter, a method returning Optional<List<Order>>. |
أظهر الحلول
- EX01
for (String w : words) if (w.length() >= min) return Optional.of(w); return Optional.empty();(or a stream withfilter(...).findFirst()). - EX02
name.map(String::toUpperCase).orElse("guest");name.orElseThrow(() -> new IllegalStateException("name missing")). - EX03 Make the field a plain
String(possibly null, documented) or keep it as a normal value; take a plainInteger/intor use overloads; returnList<Order>and an empty list when nothing is found. - Outcome 1 is also covered by the lab and quiz Q01–Q03.
الاختبار
Outcomes: O1 returning Optional · O2 transforming and unwrapping · O3 where not to use it.
اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.
الجزء العملي
Three exercises BEG-037-EX01 to EX03 plus the lab. Pass: all three exercises correct and the lab has no unchecked .get().
أخطاء شائعة
optional.get() unconditionally; Optional fields.
التقييم
3 exercises.
الصلة بالمسار الوظيفي
Spring Data return types (JNR-029).