How do I list, map and “print if count>0” with Java 8 / stream API?
Here's my code as per now.
List<Cat> cats = petStore.getCatsForSale();
if (!cats.empty)
logger.info("Processing for cats: " + cats.size());
for (Cat cat : cats) {
cat.giveFood();
}
My colleague writes realy nice code using the Java stream API. I tried to rewrite it as one streaming statement, but I got stuck.
petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
.countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
How can I do this? Ideally I want a single streaming statement...
java java-8 functional-programming java-stream
add a comment |
Here's my code as per now.
List<Cat> cats = petStore.getCatsForSale();
if (!cats.empty)
logger.info("Processing for cats: " + cats.size());
for (Cat cat : cats) {
cat.giveFood();
}
My colleague writes realy nice code using the Java stream API. I tried to rewrite it as one streaming statement, but I got stuck.
petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
.countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
How can I do this? Ideally I want a single streaming statement...
java java-8 functional-programming java-stream
2
What iscount
? Do you expect a log statement for every non empty cat?
– Tim Biegeleisen
16 hours ago
add a comment |
Here's my code as per now.
List<Cat> cats = petStore.getCatsForSale();
if (!cats.empty)
logger.info("Processing for cats: " + cats.size());
for (Cat cat : cats) {
cat.giveFood();
}
My colleague writes realy nice code using the Java stream API. I tried to rewrite it as one streaming statement, but I got stuck.
petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
.countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
How can I do this? Ideally I want a single streaming statement...
java java-8 functional-programming java-stream
Here's my code as per now.
List<Cat> cats = petStore.getCatsForSale();
if (!cats.empty)
logger.info("Processing for cats: " + cats.size());
for (Cat cat : cats) {
cat.giveFood();
}
My colleague writes realy nice code using the Java stream API. I tried to rewrite it as one streaming statement, but I got stuck.
petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
.countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
How can I do this? Ideally I want a single streaming statement...
java java-8 functional-programming java-stream
java java-8 functional-programming java-stream
edited 6 hours ago
Peter Mortensen
13.6k1984111
13.6k1984111
asked 16 hours ago
vikingstevevikingsteve
25.6k1179116
25.6k1179116
2
What iscount
? Do you expect a log statement for every non empty cat?
– Tim Biegeleisen
16 hours ago
add a comment |
2
What iscount
? Do you expect a log statement for every non empty cat?
– Tim Biegeleisen
16 hours ago
2
2
What is
count
? Do you expect a log statement for every non empty cat?– Tim Biegeleisen
16 hours ago
What is
count
? Do you expect a log statement for every non empty cat?– Tim Biegeleisen
16 hours ago
add a comment |
4 Answers
4
active
oldest
votes
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
3
@CommonMan not really, its empty vs non-empty here. I doubtOptional
would be useful here much.
– nullpointer
15 hours ago
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
@Spara so that I have a "wrapper"-stream around theCat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Usingcats.stream()
though will give you a stream over all cats (Stream<Cat>
)
– Lino
15 hours ago
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
|
show 12 more comments
Your current code is much better without a stream and can further be cut short to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I thinksingle streaming statement
is what he is looking for.
– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams
– vikingsteve
15 hours ago
2
In my opinion, is this the only acceptable solution. Don't do everything withStream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess
– Lino
15 hours ago
add a comment |
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
4
Starting fromjava-9
you may leave your cats hungry ))). Execution ofpeek
is not guaranteed anymore. Please read javadoc for more details.
– ETO
15 hours ago
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
@oleg.cherednik Yes, I know. Usingpeek
for non-debugging purposes is considered harmful anyway.
– ETO
15 hours ago
3
Moreover, starting from February 2019 there is no long-term support ofjava-8
for cemmercial users. So if you writejava-8
code, consider avoiding potential migration bugs. One may not notice thatjava-9
'speek
is not working as it did before. Thus your code will have a hidden unobvious bug.
– ETO
15 hours ago
|
show 3 more comments
I agree with @Lino. This is another alternative based on his idea:
List<Cat> cats = petStore.getCatsForSale();
cats.stream().limit(1)
.flatMap(c -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
}).forEach(Cat::giveFood);
Why not use anIntStream.range(1)
? No need to usecats.stream().limit(1)
that way
– Lino
15 hours ago
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54530220%2fhow-do-i-list-map-and-print-if-count0-with-java-8-stream-api%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
3
@CommonMan not really, its empty vs non-empty here. I doubtOptional
would be useful here much.
– nullpointer
15 hours ago
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
@Spara so that I have a "wrapper"-stream around theCat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Usingcats.stream()
though will give you a stream over all cats (Stream<Cat>
)
– Lino
15 hours ago
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
|
show 12 more comments
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
3
@CommonMan not really, its empty vs non-empty here. I doubtOptional
would be useful here much.
– nullpointer
15 hours ago
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
@Spara so that I have a "wrapper"-stream around theCat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Usingcats.stream()
though will give you a stream over all cats (Stream<Cat>
)
– Lino
15 hours ago
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
|
show 12 more comments
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
edited 6 hours ago
Peter Mortensen
13.6k1984111
13.6k1984111
answered 15 hours ago
LinoLino
8,43322037
8,43322037
3
@CommonMan not really, its empty vs non-empty here. I doubtOptional
would be useful here much.
– nullpointer
15 hours ago
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
@Spara so that I have a "wrapper"-stream around theCat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Usingcats.stream()
though will give you a stream over all cats (Stream<Cat>
)
– Lino
15 hours ago
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
|
show 12 more comments
3
@CommonMan not really, its empty vs non-empty here. I doubtOptional
would be useful here much.
– nullpointer
15 hours ago
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
@Spara so that I have a "wrapper"-stream around theCat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Usingcats.stream()
though will give you a stream over all cats (Stream<Cat>
)
– Lino
15 hours ago
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
3
3
@CommonMan not really, its empty vs non-empty here. I doubt
Optional
would be useful here much.– nullpointer
15 hours ago
@CommonMan not really, its empty vs non-empty here. I doubt
Optional
would be useful here much.– nullpointer
15 hours ago
3
3
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
@nullpointer I don't really like any of the solutions here except the one from you, I think using Streams for everyday logic is just overkill and makes it extremly hard to understand the simplest of logic
– Lino
15 hours ago
1
1
@Spara so that I have a "wrapper"-stream around the
Cat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Using cats.stream()
though will give you a stream over all cats (Stream<Cat>
)– Lino
15 hours ago
@Spara so that I have a "wrapper"-stream around the
Cat
-list (Stream<List<Cat>>
) which allows me to operate on the whole list at once, but still inside the stream. Using cats.stream()
though will give you a stream over all cats (Stream<Cat>
)– Lino
15 hours ago
3
3
@Lino well, it already is! :P
– nullpointer
15 hours ago
@Lino well, it already is! :P
– nullpointer
15 hours ago
3
3
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
@vikingsteve Do not prefer fancy streams over readability.
– ETO
15 hours ago
|
show 12 more comments
Your current code is much better without a stream and can further be cut short to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I thinksingle streaming statement
is what he is looking for.
– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams
– vikingsteve
15 hours ago
2
In my opinion, is this the only acceptable solution. Don't do everything withStream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess
– Lino
15 hours ago
add a comment |
Your current code is much better without a stream and can further be cut short to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I thinksingle streaming statement
is what he is looking for.
– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams
– vikingsteve
15 hours ago
2
In my opinion, is this the only acceptable solution. Don't do everything withStream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess
– Lino
15 hours ago
add a comment |
Your current code is much better without a stream and can further be cut short to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
Your current code is much better without a stream and can further be cut short to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
edited 6 hours ago
Peter Mortensen
13.6k1984111
13.6k1984111
answered 15 hours ago
nullpointernullpointer
47.6k11100192
47.6k11100192
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I thinksingle streaming statement
is what he is looking for.
– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams
– vikingsteve
15 hours ago
2
In my opinion, is this the only acceptable solution. Don't do everything withStream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess
– Lino
15 hours ago
add a comment |
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I thinksingle streaming statement
is what he is looking for.
– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams
– vikingsteve
15 hours ago
2
In my opinion, is this the only acceptable solution. Don't do everything withStream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess
– Lino
15 hours ago
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I'm under the impression that the OP wants to only log the number of non empty cats, not the original collection size.
– Tim Biegeleisen
15 hours ago
I think
single streaming statement
is what he is looking for.– Prashant Zombade
15 hours ago
I think
single streaming statement
is what he is looking for.– Prashant Zombade
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
@TimBiegeleisen well I chose to implement what the actual code really does and considering want a single streaming statement.. is not to check for the functional correctness in the code.
– nullpointer
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write
"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams– vikingsteve
15 hours ago
Hi and thx for answer. Can this be done in a one liner? Of course I can write
"if (!cats.isEmpty()) logger.info("...")
but the purpose of this question is to write it with streams– vikingsteve
15 hours ago
2
2
In my opinion, is this the only acceptable solution. Don't do everything with
Stream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess– Lino
15 hours ago
In my opinion, is this the only acceptable solution. Don't do everything with
Stream
s just because a tutorial told you so, just by looking at every answer here it's clear what the intentions of this one here is, but for every other? It's just a mess– Lino
15 hours ago
add a comment |
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
4
Starting fromjava-9
you may leave your cats hungry ))). Execution ofpeek
is not guaranteed anymore. Please read javadoc for more details.
– ETO
15 hours ago
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
@oleg.cherednik Yes, I know. Usingpeek
for non-debugging purposes is considered harmful anyway.
– ETO
15 hours ago
3
Moreover, starting from February 2019 there is no long-term support ofjava-8
for cemmercial users. So if you writejava-8
code, consider avoiding potential migration bugs. One may not notice thatjava-9
'speek
is not working as it did before. Thus your code will have a hidden unobvious bug.
– ETO
15 hours ago
|
show 3 more comments
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
4
Starting fromjava-9
you may leave your cats hungry ))). Execution ofpeek
is not guaranteed anymore. Please read javadoc for more details.
– ETO
15 hours ago
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
@oleg.cherednik Yes, I know. Usingpeek
for non-debugging purposes is considered harmful anyway.
– ETO
15 hours ago
3
Moreover, starting from February 2019 there is no long-term support ofjava-8
for cemmercial users. So if you writejava-8
code, consider avoiding potential migration bugs. One may not notice thatjava-9
'speek
is not working as it did before. Thus your code will have a hidden unobvious bug.
– ETO
15 hours ago
|
show 3 more comments
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
edited 15 hours ago
answered 15 hours ago
oleg.cherednikoleg.cherednik
6,67821118
6,67821118
4
Starting fromjava-9
you may leave your cats hungry ))). Execution ofpeek
is not guaranteed anymore. Please read javadoc for more details.
– ETO
15 hours ago
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
@oleg.cherednik Yes, I know. Usingpeek
for non-debugging purposes is considered harmful anyway.
– ETO
15 hours ago
3
Moreover, starting from February 2019 there is no long-term support ofjava-8
for cemmercial users. So if you writejava-8
code, consider avoiding potential migration bugs. One may not notice thatjava-9
'speek
is not working as it did before. Thus your code will have a hidden unobvious bug.
– ETO
15 hours ago
|
show 3 more comments
4
Starting fromjava-9
you may leave your cats hungry ))). Execution ofpeek
is not guaranteed anymore. Please read javadoc for more details.
– ETO
15 hours ago
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
@oleg.cherednik Yes, I know. Usingpeek
for non-debugging purposes is considered harmful anyway.
– ETO
15 hours ago
3
Moreover, starting from February 2019 there is no long-term support ofjava-8
for cemmercial users. So if you writejava-8
code, consider avoiding potential migration bugs. One may not notice thatjava-9
'speek
is not working as it did before. Thus your code will have a hidden unobvious bug.
– ETO
15 hours ago
4
4
Starting from
java-9
you may leave your cats hungry ))). Execution of peek
is not guaranteed anymore. Please read javadoc for more details.– ETO
15 hours ago
Starting from
java-9
you may leave your cats hungry ))). Execution of peek
is not guaranteed anymore. Please read javadoc for more details.– ETO
15 hours ago
1
1
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
@ETO Please look at tags. It says java-8!
– oleg.cherednik
15 hours ago
3
3
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
@oleg.cherednik I think ETO wanted to say that this solution may only work for java-8 which makes it not a favorable solution when one wants to migrate the version upwards :)
– Lino
15 hours ago
2
2
@oleg.cherednik Yes, I know. Using
peek
for non-debugging purposes is considered harmful anyway.– ETO
15 hours ago
@oleg.cherednik Yes, I know. Using
peek
for non-debugging purposes is considered harmful anyway.– ETO
15 hours ago
3
3
Moreover, starting from February 2019 there is no long-term support of
java-8
for cemmercial users. So if you write java-8
code, consider avoiding potential migration bugs. One may not notice that java-9
's peek
is not working as it did before. Thus your code will have a hidden unobvious bug.– ETO
15 hours ago
Moreover, starting from February 2019 there is no long-term support of
java-8
for cemmercial users. So if you write java-8
code, consider avoiding potential migration bugs. One may not notice that java-9
's peek
is not working as it did before. Thus your code will have a hidden unobvious bug.– ETO
15 hours ago
|
show 3 more comments
I agree with @Lino. This is another alternative based on his idea:
List<Cat> cats = petStore.getCatsForSale();
cats.stream().limit(1)
.flatMap(c -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
}).forEach(Cat::giveFood);
Why not use anIntStream.range(1)
? No need to usecats.stream().limit(1)
that way
– Lino
15 hours ago
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
add a comment |
I agree with @Lino. This is another alternative based on his idea:
List<Cat> cats = petStore.getCatsForSale();
cats.stream().limit(1)
.flatMap(c -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
}).forEach(Cat::giveFood);
Why not use anIntStream.range(1)
? No need to usecats.stream().limit(1)
that way
– Lino
15 hours ago
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
add a comment |
I agree with @Lino. This is another alternative based on his idea:
List<Cat> cats = petStore.getCatsForSale();
cats.stream().limit(1)
.flatMap(c -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
}).forEach(Cat::giveFood);
I agree with @Lino. This is another alternative based on his idea:
List<Cat> cats = petStore.getCatsForSale();
cats.stream().limit(1)
.flatMap(c -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
}).forEach(Cat::giveFood);
edited 6 hours ago
Peter Mortensen
13.6k1984111
13.6k1984111
answered 15 hours ago
David Pérez CabreraDavid Pérez Cabrera
3,88321231
3,88321231
Why not use anIntStream.range(1)
? No need to usecats.stream().limit(1)
that way
– Lino
15 hours ago
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
add a comment |
Why not use anIntStream.range(1)
? No need to usecats.stream().limit(1)
that way
– Lino
15 hours ago
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
Why not use an
IntStream.range(1)
? No need to use cats.stream().limit(1)
that way– Lino
15 hours ago
Why not use an
IntStream.range(1)
? No need to use cats.stream().limit(1)
that way– Lino
15 hours ago
1
1
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
@Lino because of empty list
– David Pérez Cabrera
15 hours ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54530220%2fhow-do-i-list-map-and-print-if-count0-with-java-8-stream-api%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
What is
count
? Do you expect a log statement for every non empty cat?– Tim Biegeleisen
16 hours ago