import java.util.Comparator;
import java.util.PriorityQueue;
public class TestPQ {
public static void main(String[] args){
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
queue.offer("Short");
queue.offer("ABCahahahha");
queue.offer("lululu");
queue.stream().map( s-> {
System.out.println("queue: "+ s);
return s;
});
}
}
I have this code and I expect that I would see "Short", "lululu" and "ABCahahahha" been printed out. But I don't see them. what's wrong with my code? Compile is fine. and I am using java 8 compiler and runtime.
You don't have any terminal operation consuming your stream. So nothing happens. map()
is an intermediate operation, which is not supposed to have side effects. What your code should be is
queue.stream().forEach(s-> {
System.out.println("queue: "+ s);
});
The map() method itself is intermediate and does not enforce the consumption of a Stream
so it's a very bad idea to put side effects there.
In this case, you should use the dedicated forEach() method:
queue.stream()
.forEach(s -> System.out.println("queue: " + s));
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