Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java8 Stream generate nothing?

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.

like image 281
BufBills Avatar asked Apr 20 '15 21:04

BufBills


2 Answers

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);
});
like image 131
JB Nizet Avatar answered Sep 30 '22 15:09

JB Nizet


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));
like image 39
Grzegorz Piwowarek Avatar answered Sep 30 '22 14:09

Grzegorz Piwowarek