Memory overhead of `Option` in Rust is not constant

Using the following snippet use std::mem; fn main() { println!("size Option(bool): {} ({})", mem::size_of::<Option<bool>>(), mem::size_of::<bool>()); println!("size Option(u8): {} ({})", mem::size_of::<Option<u8>>(), mem::size_of::<u8>()); println!("size Option(u16): {} ({})", mem::size_of::<Option<u16>>(), mem::size_of::<u16>()); println!("size Option(u32): {} ({})", mem::size_of::<Option<u32>>(), mem::size_of::<u32>()); println!("size Option(u64): {} ({})", mem::size_of::<Option<u64>>(), mem::size_of::<u64>()); println!("size Option(u128): {} ({})", mem::size_of::<Option<u128>>(), mem::size_of::<u128>()) } I see on my 64-bits machine: size Option(bool): 1… Read More Memory overhead of `Option` in Rust is not constant

Conditionals using Optional

Is there a way to change the conditional statement using Optional library? Optional<String> fruit = Optional.of("Apple"); fruit.isPresent() ? "Fruit Present" : "Fruit not present"; >Solution : It is little bit weird since argument of map function is ignored, anyway it is equivalent to ?:. fruit.map(currentElement -> "Fruit Present").orElse("Fruit not present")

How to get rid of NullPointerException in a method using Streams API and Optional?

Given the following task. We have an Employee and a Company classes. Each instance of Employee class is stored in array Employee[] employees in the Company class. I need a method which finds an instance of Employee in the array Employee[] employees by id. I managed to write the following code: public class Employee {… Read More How to get rid of NullPointerException in a method using Streams API and Optional?

How to use optional if it is present then call a method of this object, other wise return null

Optional<CustomerEntity> findById(Integer id) { return Optional.ofNullable(em.find(CustomerEntity.class, Long.valueOf(id))); } public List<Booking> getBooking(Integer id) { return customerRepository.findById(id).get().getBooking(); } The problem is findById might return null, so I want something like customerRepository.findById(id).ifPresent().getBooking(); I could do it by manually check the ifpresent() return value, but I want to make it one line if possible. >Solution : You can use… Read More How to use optional if it is present then call a method of this object, other wise return null