Java 11 Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The following code demonstrates the functionality of the described Optional class. The useFlatMap() method accepts a list of Optional objects, creates a stream, and process each emitted element:

void useFlatMap(List<Optional<Integer>> list){
Function<Optional<Integer>,
Stream<Optional<Integer>>> tryUntilWin = opt -> {
List<Optional<Integer>> opts = new ArrayList<>();
if(opt.isPresent()){
opts.add(opt);
} else {
int prize = 0;
while(prize == 0){
double d = Math.random() - 0.8;
prize = d > 0 ? (int)(1000000 * d) : 0;
opts.add(Optional.of(prize));
}
}
return opts.stream();
};
list.stream().flatMap(tryUntilWin)
.forEach(opt -> checkResultAndShare(opt.get()));
}

Each element of the original list first enters the flatMap() method as an input into the tryUntilWin function. This function first checks if the value of the Optional object is present. If yes, the Optional object is emitted as a single element of a stream and is processed by the checkResultAndShare() method. But if the tryUntilWin function determines that there is no value in the Optional object or the value is null, it generates a random double number in the range between -0.8 and 0.2. If the value is negative, an Optional object is added to the resulting list with a value of zero and a new random number is generated. But if the generated number is positive, it is used for the prize-value calculation, which is added to the resulting list that's wrapped inside an Optional object. The resulting list of Optional objects is then returned as a stream, and each element of the stream is processed by the checkResultAndShare() method.

Now, let's run the preceding method for the following list:

List<Optional<Integer>> list = List.of(Optional.empty(), 
Optional.ofNullable(null),
Optional.of(100000));
useFlatMap(list);

The results will be as follows:

As you can see, when the first list element, Optional.empty(), was processed, the tryUntilWin function succeeded in getting a positive prize value from the third attempt. The second Optional.ofNullable(null) object caused two attempts until the tryUntilWin function succeeded. The last object successfully went through and awarded you and your friend 50,000 each.