为什么 Java8 Stream 什么都不生成?什么都不、Stream

由网友(他是暖光不会发光)分享简介:import java.util.Comparator;import java.util.PriorityQueue;public class TestPQ {public static void main(String[] args){Comparator comparator = new Stri...
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;
        });
    }
}

我有这个代码,我希望我会看到Short"、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() 方法本身是 intermediate 并且不强制使用 所以把副作用放在那里是一个非常糟糕的主意.

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));
阅读全文

相关推荐

最新文章