Java की Optional Class
In this page:
Optional<Type> optional = Optional.ofNullable(value);
optional.isPresent();
optional.orElse(defaultValue);
optional.ifPresent(value -> action);
What is Optional?
Optional class एक container object है जिसे specifically किसी value की मौजूदगी या अनुपस्थिति को represent करने के लिए डिज़ाइन किया गया है, बिना किसी bare null reference के उपयोग के। यह आपको missing values को सुरक्षित रूप से handle करने में मदद करता है और किसी method के return type में 'कोई value नहीं' की संभावना को, एक implicit, undocumented जोखिम होने के बजाय, दिखाई देने योग्य बनाता है।
उदाहरण: What is Optional?
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> name = Optional.of("Meera");
// Optional wraps a value that may be absent
Optional<String> empty = Optional.empty();
// Print a line to the console
System.out.println(name.isPresent() + " " + empty.isPresent());
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Presence and Retrieving Values
आप isPresent() का उपयोग करके जांच सकते हैं कि किसी Optional के अंदर कोई value मौजूद है या नहीं, और सिर्फ तभी कुछ code चलाने के लिए जब कोई value वाकई मौजूद हो, इसके बजाय ifPresent() method का उपयोग करें, जो एक explicit if-check को पूरी तरह टाल देता है।
उदाहरण: Checking Presence and Retrieving Values
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> value = Optional.of("data");
// Check whether value.isPresent()
if (value.isPresent()) {
// Print a line to the console
System.out.println(value.get());
}
value.ifPresent(v -> System.out.println("Present: " + v));
}
}
Login to try C/C++/Java/PHP code in the editor
Safe Fallback Methods
आप Optional के खाली निकलने पर उपयोग करने के लिए एक fallback default provide कर सकते हैं, या तो orElse() का उपयोग करके, जो हमेशा default को eagerly compute करता है, या orElseGet() का उपयोग करके, जो सिर्फ तभी एक supplier के ज़रिए lazily इसे compute करता है जब वाकई ज़रूरत हो।
उदाहरण: Safe Fallback Methods
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> empty = Optional.empty();
// Print a line to the console
System.out.println(empty.orElse("default value"));
// Print a line to the console
System.out.println(empty.orElseGet(() -> "computed lazily"));
}
}
Login to try C/C++/Java/PHP code in the editor
Throwing Exceptions with Optional
अगर आप किसी missing value को सीधे तौर पर एक error माना जाना चाहते हैं, तो चुपचाप fallback करने के बजाय एक चुना हुआ exception फेंकने के लिए orElseThrow() method का उपयोग करें। यह आपको यह जांचने का एक साफ़, explicit तरीका देता है कि आगे बढ़ने से पहले एक optional input असल में प्रदान किया गया था।
उदाहरण: Throwing Exceptions with Optional
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<String> value = Optional.of("present");
// Print a line to the console
System.out.println(value.orElseThrow(() -> new IllegalStateException("missing value")));
}
}
Login to try C/C++/Java/PHP code in the editor
Transforming Optionals
आप filter() और map() का उपयोग करके किसी Optional के अंदर की value को transform कर सकते हैं, आपको conditions और conversions को एक pipeline में साथ chain करने देते हुए जो किसी भी step के fail होने पर अपने आप खाली में short-circuit हो जाता है — बहुत कुछ उसी भावना में जैसे एक Stream pipeline व्यवहार करता है।
उदाहरण: Transforming Optionals
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Optional wraps a value that may be absent
Optional<Integer> result = Optional.of(10)
.filter(n -> n > 5)
.map(n -> n * 2);
// Print a line to the console
System.out.println(result.get());
}
}
Login to try C/C++/Java/PHP code in the editor
- बिना जांचे
opt.get()call करना, जो Optional के खाली होने परNoSuchElementExceptionफेंकता है; पहलेorElse,ifPresentयाisPresentका उपयोग करें। Optional.of(value)को ऐसी value के साथ उपयोग करना जो null हो सकती है, जोNullPointerExceptionफेंकता है;Optional.ofNullableका उपयोग करें।orElse(expensiveCall())लिखना, जो value मौजूद होने पर भी हमेशा call चलाता है; इसे सिर्फ ज़रूरत पड़ने पर चलाने के लिएorElseGet(() -> expensiveCall())का उपयोग करें।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: