android


Return a List of Object from a List of Optional objects


Consider i have an array list of Optional objects like List visit = {Optional[Visit], Optional[Visit], etc}. How do i get the Visit object from the Optional and just return those objects as a list.
i tried something like this:
return Stream.of(visits).filter(value -> Optional.isPresent(value))
.map((Visit t) -> Optional.get(t))
.collect(Collectors.toList());
and this:
return Stream.of(visits)
.map(visit -> Optional.of(visit).get())
.collect(Collectors.toList());
But this doesn't compile.Am trying to use http://annimon.github.io/Lightweight-Stream-API for this. Any help will be greatly appreciated.Thanks
You may do it this way:
return visits.stream()
.map(visit -> visit.orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
Assuming visits is of type List<Optional<Visit>>.
Causes Of Your Code Not Compiling
Assuming that the variable visits is of type List<Optional<Visit>> the statement you posted:
Stream.of(visits).filter(value -> Optional.isPresent(value))
.map((Visit t) -> Optional.get(t))
.collect(Collectors.toList());
has the following problems:
Stream.of() takes either one element or many elements of type T and creates a Stream. You use visits as one element of type List<Optional<Visit>> and I think you intend to get a Stream of Optional<Visit> which you may achieve by using visits.stream().
filter(value -> Optional.isPresent(value)) does invoke isPresent(T t) in a static way while the method isPresent(T t) doesn't exist, neither statically nor as an instance method. I think what you intend to do is: filter(value -> value.isPresent()) which is equal to filter(Optional::isPresent). The difference of the second is that Optional::isPresent does not invoke a static method but results in a method reference.
map((Visit) t -> Optional.get(t)) does as well invoke a method get(T t) in a static way which doesn't exist, neither statically nor as an instance method. I think you intended to invoke map((Visit) t -> t.get()) which is equal to map(Optional::get).
Fixing those issues would result in the new statement:
visits.stream().filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
The difference to my solution is only that you map after filter. As a reader to get it right you need to remember that Optional::get will always return a non-null value. If you map first and filter second you do not have to remember there are no null values because you filter them out in the second step.
You could do it as follows:
List<Visit> visitsWithoutOptionals = visits.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());

Related Links

I can't use sharedpreferences without android app crashing
accept call working but goes on hold android programmetically
Retrofit REST request with '=' in body
Image Mapping On android
When a parcelable object is passed through an intent, does it update with references to the original object?
Firebase Auth - No Provider Data on Android
How to float left drawable with (hint) label in TextInputLayout?
BitmapCreateBitmap Out of Memory
Edge glow is not displayed over transparent background
Wrong TextView display in constraintlayout when anysize
Older Android OS showing styling weirdly in menus / edit text / buttons
android.content.ActivityNotFoundException: Unable to find explicit activity class - how to fix it?
Strings not sending proprerly over Bluetooth [Android App]
Migrating Parse DB to mLab
Google Places-API statusCode = PLACES_API_ACCESS_NOT_CONFIGURED
Android Fragment Animation for custom views

Categories

HOME
url-redirection
kentico
oracle12c
paraview
merge
css3
mysql-workbench
yahoo-finance
bitbucket-api
javacc
carousel
visual-studio-emulator
bing-maps
ibeacon-android
plist
java.util.logging
php-5.6
shared-libraries
http-post
mvc-mini-profiler
soci
gmm
href
draft-js-plugins
fragment-backstack
nstimer
8051
intersystems-cache
xbox
fstream
instantiation
getpixel
html-encode
servicestack-text
xajax
sharepoint-workflow
openalpr
amazon-ses
filesystemwatcher
metawidget
jvmti
urlsession
signals-slots
tcc
openresty
reportservice2010
openblas
headless
payload
mach-o
javafx-css
materialized-path-pattern
rocks
node-request
pytables
http-status-code-401
nservicebus5
dbamp
phpwebsocket
sklearn-pandas
html-to-pdf
grass
exim4
concurrentmodification
java-money
toolkit
evolus-pencil
viola-jones
actionfilterattribute
mmwormhole
qtwebengine
psr-4
reflector
wxformbuilder
spring-3
ie8-compatibility-mode
breakout
beaker-testing
swfobject
resource-management
intersect
patricia-trie
pyunit
rmiregistry
cuda-gdb
extconf.rb
fusefabric
httponly
floating-point-exceptions
stress
cgbitmapcontextcreate
event-receiver
tmx
django-paypal
diagrams
timertask
echo3

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App