The following code converts a list of objects into a list of optional objects. Is there an elegant way to do this using Java 8's streams?
List<Object> originalList = Arrays.asList(new Object(), new Object());
List<Optional<Object>> convertedList = new ArrayList<>();
for (Object object : originalList) {
convertedList.add(Optional.of(object));
}
I tried the following piece of code.
List<Optional<Object>> convertedList = originalList.stream().map((o) -> Optional.of(o));
However this gives the following compile error:
of(T) in Optional cannot be applied to (java.lang.Object)
This is using the java.util.Optional class rather than the Guava one.
Programmers can also use the ofNullable() method, which will return an empty Optional object if the value is null, or an Optional object containing the given value if it is non-null. Finally, you can create an empty Optional object using the empty() method.
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
list() function in R Programming Language is used to convert an object to a list.
You forgot to collect the elements of the Stream
in a list. It should be:
List<Optional<Object>> convertedList = originalList.stream()
.map((o) -> Optional.of(o))
.collect(Collectors.toList());
//or .collect(Collectors.toCollection(LinkedList::new)); if you want a specific List implementation
Note that you could avoid the creation of a lamdba and use a method reference in this case with .map(Optional::of)
.
I don't see why you would get a List
of Optional
if you know in advance that the elements in the list are non-null. Maybe it was just to get in practice with Java 8, but as @Eran said you should use Optional::ofNullable
instead.
It looks like you forgot to collect the Stream to a list :
List<Optional<Object>> convertedList =
originalList.stream()
.map((o) -> Optional.ofNullable(o))
.collect(Collectors.toList());
You should use ofNullable
though, since of
required a non null object (it will throw a NullPointerException
when passed a null reference).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With