为什么Java8 Stream什么都没产生? [英] Why does Java8 Stream generate nothing?
本文介绍了为什么Java8 Stream什么都没产生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
});
}
}
我有这个代码,我希望我会看到短,lululu和ABCahahahha被打印出来。
但是我没有看到它们。我的代码出了什么问题?
编译没问题。我正在使用java 8编译器和运行时。
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.
推荐答案
map()方法本身是 middle 并且不强制消耗 Stream
所以将副作用放在那里是一个非常糟糕的主意。
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.
在这种情况下,您应该使用专用的 forEach()方法:
In this case, you should use the dedicated forEach() method:
queue.stream()
.forEach(s -> System.out.println("queue: " + s));
这篇关于为什么Java8 Stream什么都没产生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文