Effective Java



Download 2,19 Mb.
Pdf ko'rish
bet198/341
Sana11.07.2022
Hajmi2,19 Mb.
#776765
1   ...   194   195   196   197   198   199   200   201   ...   341
Bog'liq
Effective Java



ITEM 47: PREFER COLLECTION TO STREAM AS A RETURN TYPE
217
This client code works, but it is too noisy and opaque to use in practice. A better
workaround is to use an adapter method. The JDK does not provide such a
method, but it’s easy to write one, using the same technique used in-line in the
snippets above. Note that no cast is necessary in the adapter method because
Java’s type inference works properly in this context:
// Adapter from Stream to Iterable
public static Iterable iterableOf(Stream stream) {
return stream::iterator;
}
With this adapter, you can iterate over any stream with a for-each statement:
for (ProcessHandle p : iterableOf(ProcessHandle.allProcesses())) {
// Process the process
}
Note that the stream versions of the 
Anagrams
program in Item 34 use the
Files.lines
method to read the dictionary, while the iterative version uses a
scanner. The 
Files.lines
method is superior to a scanner, which silently
swallows any exceptions encountered while reading the file. Ideally, we would
have used 
Files.lines
in the iterative version too. This is the sort of compromise
that programmers will make if an API provides only stream access to a sequence
and they want to iterate over the sequence with a for-each statement.
Conversely, a programmer who wants to process a sequence using a stream
pipeline will be justifiably upset by an API that provides only an 
Iterable
. Again
the JDK does not provide an adapter, but it’s easy enough to write one:

Download 2,19 Mb.

Do'stlaringiz bilan baham:
1   ...   194   195   196   197   198   199   200   201   ...   341




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish