How to get the first first element while continue streaming?2019 Community Moderator ElectionCan I add jars...
Make me a metasequence
Why is it "take a leak?"
I encountered my boss during an on-site interview at another company. Should I bring it up when seeing him next time?
Four buttons on a table
Plagiarism of code by other PhD student
Is there any relevance to Thor getting his hair cut other than comedic value?
"seeing as you don't know anyone but me" meaning in this context
Can a space-faring robot still function over a billion years?
How to roleplay my character's ethics according to the DM when I don't understand those ethics?
How to mitigate "bandwagon attacking" from players?
"Lived a lion" or "there lived a lion"
Levi-Civita symbol: 3D matrix
Is there a math equivalent to the conditional ternary operator?
Is it possible to counterspell the revised Artificer?
Which sins are beyond punishment?
How to get the first first element while continue streaming?
Is there a frame of reference in which I was born before I was conceived?
Would the melodic leap of the opening phrase of Mozart's K545 be considered dissonant?
A bug in Excel? Conditional formatting for marking duplicates also highlights unique value
Movie: Scientists travel to the future to avoid nuclear war, last surviving one is used as fuel by future humans
In which way proportional valves are controlled solely by current?
What does each site of a vanilla 9.1 installation do?
Does "legal poaching" exist?
Is the NES controller port identical to the port on a Wii remote?
How to get the first first element while continue streaming?
2019 Community Moderator ElectionCan I add jars to maven 2 build classpath without installing them?How to get an enum value from a string value in Java?Efficiency of Java “Double Brace Initialization”?Get last element of Stream/List in a one-linerUsing Java 8's Optional with Stream::flatMapHow to Convert a Java 8 Stream to an Array?Find first element by predicateConvert Iterable to Stream using Java 8 JDKSpecial behavior of a stream if there are no elementsStream Way to get index of first element matching boolean
I have a stream of generic items. I'd like to print the class name of the first item + the toString()
of all the items.
If I had an Iterable, it would look like this:
Iterable<E> itemIter = ...;
boolean first = true;
for (E e : itemIter) {
if (first) {
first = false;
System.out.println(e.getClass().getSimpleName());
}
System.out.println(e);
}
Any idea if I can do this on a stream (Stream<T>
) with stream api? Thanks.
UPDATE: Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
java java-stream
add a comment |
I have a stream of generic items. I'd like to print the class name of the first item + the toString()
of all the items.
If I had an Iterable, it would look like this:
Iterable<E> itemIter = ...;
boolean first = true;
for (E e : itemIter) {
if (first) {
first = false;
System.out.println(e.getClass().getSimpleName());
}
System.out.println(e);
}
Any idea if I can do this on a stream (Stream<T>
) with stream api? Thanks.
UPDATE: Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
java java-stream
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago
add a comment |
I have a stream of generic items. I'd like to print the class name of the first item + the toString()
of all the items.
If I had an Iterable, it would look like this:
Iterable<E> itemIter = ...;
boolean first = true;
for (E e : itemIter) {
if (first) {
first = false;
System.out.println(e.getClass().getSimpleName());
}
System.out.println(e);
}
Any idea if I can do this on a stream (Stream<T>
) with stream api? Thanks.
UPDATE: Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
java java-stream
I have a stream of generic items. I'd like to print the class name of the first item + the toString()
of all the items.
If I had an Iterable, it would look like this:
Iterable<E> itemIter = ...;
boolean first = true;
for (E e : itemIter) {
if (first) {
first = false;
System.out.println(e.getClass().getSimpleName());
}
System.out.println(e);
}
Any idea if I can do this on a stream (Stream<T>
) with stream api? Thanks.
UPDATE: Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
java java-stream
java java-stream
edited 8 mins ago
AlikElzin-kilaka
asked 28 mins ago
AlikElzin-kilakaAlikElzin-kilaka
18.7k15126201
18.7k15126201
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago
add a comment |
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago
add a comment |
6 Answers
6
active
oldest
votes
Stream
in Java is not reusable. This means, that consuming stream can be done only once. If you get the first element from a stream, you can iterate over it one more time.
Workaround would be to create another stream same as the first one or getting the first item and then creating a stream, something like that:
Stream<E> stream = (List<E>) itemIter).stream();
E firstElement = itemIter.next();
stream.foreach(...);
Hmmm... is there an API to duplicate astream
? What would be the memory implications?
– AlikElzin-kilaka
5 mins ago
add a comment |
There is StreamEx
library that extend standard java stream api. Using StreamEx.of(Iterator)
and peekFirst
:
StreamEx.of(itemIter.iterator())
.peekFirst(e -> System.out.println(e.getClass().getSimpleName()))
.forEach(System.out::println);
1
this is interesting!
– nullpointer
7 mins ago
add a comment |
You can abuse reduction:
Stream<E> stream = ...;
System.out.println(stream
.reduce("",(out,e) ->
out + (out.isEmpty() ? e.getClass().getSimpleName()+"n" : "")
+ e));
add a comment |
Using streams possibly in two steps as:
((List<E>) itemIter).stream()
.findFirst()
.ifPresent(e -> System.out.println(e.getClass().getSimpleName()));
((List<E>) itemIter)
.stream()
.skip(1)
.forEach(System.out::println);
or alternatively as :
IntStream.range(0, ((List<E>) itemIter).size()).mapToObj(a -> {
if (a == 0) {
return ((List<E>) itemIter).get(a).getClass().getSimpleName();
} else {
return ((List<E>) itemIter).get(a);
}
}).forEach(System.out::println);
1
Note: I believe things would have been really simplified if the backing up data structure forIterable
was clarified as well.
– nullpointer
14 mins ago
add a comment |
You could use peek
for that:
AtomicBoolean first = new AtomicBoolean(true);
itemIter.stream()
.peek(e -> {
if(first.get()) {
System.out.println(e.getClass().getSimpleName());
first.set(false);
}
})
...
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing likeitemIter.stream()
available up front.
– nullpointer
5 mins ago
add a comment |
One workaround is to do it like this -
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
static int i = 0;
static int getCounter(){
return i;
}
static void incrementCounter(){
i++;
}
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
List<String> answer = list.stream().filter(str -> {if(getCounter()==0) {System.out.println("First Element : " + str);} incrementCounter(); return true;}).
collect(Collectors.toList());
System.out.println(answer);
}
}
Output :
First Element : A
[A, B, C, D, E, F, G]
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%2f55027574%2fhow-to-get-the-first-first-element-while-continue-streaming%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Stream
in Java is not reusable. This means, that consuming stream can be done only once. If you get the first element from a stream, you can iterate over it one more time.
Workaround would be to create another stream same as the first one or getting the first item and then creating a stream, something like that:
Stream<E> stream = (List<E>) itemIter).stream();
E firstElement = itemIter.next();
stream.foreach(...);
Hmmm... is there an API to duplicate astream
? What would be the memory implications?
– AlikElzin-kilaka
5 mins ago
add a comment |
Stream
in Java is not reusable. This means, that consuming stream can be done only once. If you get the first element from a stream, you can iterate over it one more time.
Workaround would be to create another stream same as the first one or getting the first item and then creating a stream, something like that:
Stream<E> stream = (List<E>) itemIter).stream();
E firstElement = itemIter.next();
stream.foreach(...);
Hmmm... is there an API to duplicate astream
? What would be the memory implications?
– AlikElzin-kilaka
5 mins ago
add a comment |
Stream
in Java is not reusable. This means, that consuming stream can be done only once. If you get the first element from a stream, you can iterate over it one more time.
Workaround would be to create another stream same as the first one or getting the first item and then creating a stream, something like that:
Stream<E> stream = (List<E>) itemIter).stream();
E firstElement = itemIter.next();
stream.foreach(...);
Stream
in Java is not reusable. This means, that consuming stream can be done only once. If you get the first element from a stream, you can iterate over it one more time.
Workaround would be to create another stream same as the first one or getting the first item and then creating a stream, something like that:
Stream<E> stream = (List<E>) itemIter).stream();
E firstElement = itemIter.next();
stream.foreach(...);
edited 20 mins ago
answered 24 mins ago
AndronicusAndronicus
3,44921429
3,44921429
Hmmm... is there an API to duplicate astream
? What would be the memory implications?
– AlikElzin-kilaka
5 mins ago
add a comment |
Hmmm... is there an API to duplicate astream
? What would be the memory implications?
– AlikElzin-kilaka
5 mins ago
Hmmm... is there an API to duplicate a
stream
? What would be the memory implications?– AlikElzin-kilaka
5 mins ago
Hmmm... is there an API to duplicate a
stream
? What would be the memory implications?– AlikElzin-kilaka
5 mins ago
add a comment |
There is StreamEx
library that extend standard java stream api. Using StreamEx.of(Iterator)
and peekFirst
:
StreamEx.of(itemIter.iterator())
.peekFirst(e -> System.out.println(e.getClass().getSimpleName()))
.forEach(System.out::println);
1
this is interesting!
– nullpointer
7 mins ago
add a comment |
There is StreamEx
library that extend standard java stream api. Using StreamEx.of(Iterator)
and peekFirst
:
StreamEx.of(itemIter.iterator())
.peekFirst(e -> System.out.println(e.getClass().getSimpleName()))
.forEach(System.out::println);
1
this is interesting!
– nullpointer
7 mins ago
add a comment |
There is StreamEx
library that extend standard java stream api. Using StreamEx.of(Iterator)
and peekFirst
:
StreamEx.of(itemIter.iterator())
.peekFirst(e -> System.out.println(e.getClass().getSimpleName()))
.forEach(System.out::println);
There is StreamEx
library that extend standard java stream api. Using StreamEx.of(Iterator)
and peekFirst
:
StreamEx.of(itemIter.iterator())
.peekFirst(e -> System.out.println(e.getClass().getSimpleName()))
.forEach(System.out::println);
edited 6 mins ago
answered 10 mins ago
RuslanRuslan
2,980822
2,980822
1
this is interesting!
– nullpointer
7 mins ago
add a comment |
1
this is interesting!
– nullpointer
7 mins ago
1
1
this is interesting!
– nullpointer
7 mins ago
this is interesting!
– nullpointer
7 mins ago
add a comment |
You can abuse reduction:
Stream<E> stream = ...;
System.out.println(stream
.reduce("",(out,e) ->
out + (out.isEmpty() ? e.getClass().getSimpleName()+"n" : "")
+ e));
add a comment |
You can abuse reduction:
Stream<E> stream = ...;
System.out.println(stream
.reduce("",(out,e) ->
out + (out.isEmpty() ? e.getClass().getSimpleName()+"n" : "")
+ e));
add a comment |
You can abuse reduction:
Stream<E> stream = ...;
System.out.println(stream
.reduce("",(out,e) ->
out + (out.isEmpty() ? e.getClass().getSimpleName()+"n" : "")
+ e));
You can abuse reduction:
Stream<E> stream = ...;
System.out.println(stream
.reduce("",(out,e) ->
out + (out.isEmpty() ? e.getClass().getSimpleName()+"n" : "")
+ e));
edited 3 mins ago
answered 21 mins ago
Benjamin UrquhartBenjamin Urquhart
705
705
add a comment |
add a comment |
Using streams possibly in two steps as:
((List<E>) itemIter).stream()
.findFirst()
.ifPresent(e -> System.out.println(e.getClass().getSimpleName()));
((List<E>) itemIter)
.stream()
.skip(1)
.forEach(System.out::println);
or alternatively as :
IntStream.range(0, ((List<E>) itemIter).size()).mapToObj(a -> {
if (a == 0) {
return ((List<E>) itemIter).get(a).getClass().getSimpleName();
} else {
return ((List<E>) itemIter).get(a);
}
}).forEach(System.out::println);
1
Note: I believe things would have been really simplified if the backing up data structure forIterable
was clarified as well.
– nullpointer
14 mins ago
add a comment |
Using streams possibly in two steps as:
((List<E>) itemIter).stream()
.findFirst()
.ifPresent(e -> System.out.println(e.getClass().getSimpleName()));
((List<E>) itemIter)
.stream()
.skip(1)
.forEach(System.out::println);
or alternatively as :
IntStream.range(0, ((List<E>) itemIter).size()).mapToObj(a -> {
if (a == 0) {
return ((List<E>) itemIter).get(a).getClass().getSimpleName();
} else {
return ((List<E>) itemIter).get(a);
}
}).forEach(System.out::println);
1
Note: I believe things would have been really simplified if the backing up data structure forIterable
was clarified as well.
– nullpointer
14 mins ago
add a comment |
Using streams possibly in two steps as:
((List<E>) itemIter).stream()
.findFirst()
.ifPresent(e -> System.out.println(e.getClass().getSimpleName()));
((List<E>) itemIter)
.stream()
.skip(1)
.forEach(System.out::println);
or alternatively as :
IntStream.range(0, ((List<E>) itemIter).size()).mapToObj(a -> {
if (a == 0) {
return ((List<E>) itemIter).get(a).getClass().getSimpleName();
} else {
return ((List<E>) itemIter).get(a);
}
}).forEach(System.out::println);
Using streams possibly in two steps as:
((List<E>) itemIter).stream()
.findFirst()
.ifPresent(e -> System.out.println(e.getClass().getSimpleName()));
((List<E>) itemIter)
.stream()
.skip(1)
.forEach(System.out::println);
or alternatively as :
IntStream.range(0, ((List<E>) itemIter).size()).mapToObj(a -> {
if (a == 0) {
return ((List<E>) itemIter).get(a).getClass().getSimpleName();
} else {
return ((List<E>) itemIter).get(a);
}
}).forEach(System.out::println);
edited 14 mins ago
answered 22 mins ago
nullpointernullpointer
43.5k10102201
43.5k10102201
1
Note: I believe things would have been really simplified if the backing up data structure forIterable
was clarified as well.
– nullpointer
14 mins ago
add a comment |
1
Note: I believe things would have been really simplified if the backing up data structure forIterable
was clarified as well.
– nullpointer
14 mins ago
1
1
Note: I believe things would have been really simplified if the backing up data structure for
Iterable
was clarified as well.– nullpointer
14 mins ago
Note: I believe things would have been really simplified if the backing up data structure for
Iterable
was clarified as well.– nullpointer
14 mins ago
add a comment |
You could use peek
for that:
AtomicBoolean first = new AtomicBoolean(true);
itemIter.stream()
.peek(e -> {
if(first.get()) {
System.out.println(e.getClass().getSimpleName());
first.set(false);
}
})
...
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing likeitemIter.stream()
available up front.
– nullpointer
5 mins ago
add a comment |
You could use peek
for that:
AtomicBoolean first = new AtomicBoolean(true);
itemIter.stream()
.peek(e -> {
if(first.get()) {
System.out.println(e.getClass().getSimpleName());
first.set(false);
}
})
...
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing likeitemIter.stream()
available up front.
– nullpointer
5 mins ago
add a comment |
You could use peek
for that:
AtomicBoolean first = new AtomicBoolean(true);
itemIter.stream()
.peek(e -> {
if(first.get()) {
System.out.println(e.getClass().getSimpleName());
first.set(false);
}
})
...
You could use peek
for that:
AtomicBoolean first = new AtomicBoolean(true);
itemIter.stream()
.peek(e -> {
if(first.get()) {
System.out.println(e.getClass().getSimpleName());
first.set(false);
}
})
...
answered 9 mins ago
LinoLino
9,76922043
9,76922043
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing likeitemIter.stream()
available up front.
– nullpointer
5 mins ago
add a comment |
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing likeitemIter.stream()
available up front.
– nullpointer
5 mins ago
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing like
itemIter.stream()
available up front.– nullpointer
5 mins ago
In that sense, I guess the code in question would be much better even if the iterable is defined. Keeping in mind there is nothing like
itemIter.stream()
available up front.– nullpointer
5 mins ago
add a comment |
One workaround is to do it like this -
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
static int i = 0;
static int getCounter(){
return i;
}
static void incrementCounter(){
i++;
}
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
List<String> answer = list.stream().filter(str -> {if(getCounter()==0) {System.out.println("First Element : " + str);} incrementCounter(); return true;}).
collect(Collectors.toList());
System.out.println(answer);
}
}
Output :
First Element : A
[A, B, C, D, E, F, G]
add a comment |
One workaround is to do it like this -
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
static int i = 0;
static int getCounter(){
return i;
}
static void incrementCounter(){
i++;
}
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
List<String> answer = list.stream().filter(str -> {if(getCounter()==0) {System.out.println("First Element : " + str);} incrementCounter(); return true;}).
collect(Collectors.toList());
System.out.println(answer);
}
}
Output :
First Element : A
[A, B, C, D, E, F, G]
add a comment |
One workaround is to do it like this -
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
static int i = 0;
static int getCounter(){
return i;
}
static void incrementCounter(){
i++;
}
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
List<String> answer = list.stream().filter(str -> {if(getCounter()==0) {System.out.println("First Element : " + str);} incrementCounter(); return true;}).
collect(Collectors.toList());
System.out.println(answer);
}
}
Output :
First Element : A
[A, B, C, D, E, F, G]
One workaround is to do it like this -
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
static int i = 0;
static int getCounter(){
return i;
}
static void incrementCounter(){
i++;
}
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
List<String> answer = list.stream().filter(str -> {if(getCounter()==0) {System.out.println("First Element : " + str);} incrementCounter(); return true;}).
collect(Collectors.toList());
System.out.println(answer);
}
}
Output :
First Element : A
[A, B, C, D, E, F, G]
answered 8 mins ago
Mohammad AdilMohammad Adil
39.4k1471100
39.4k1471100
add a comment |
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%2f55027574%2fhow-to-get-the-first-first-element-while-continue-streaming%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
Please note that it's a question about streams - not about iterators. I have a stream - not an iterator.
– AlikElzin-kilaka
4 mins ago