Elist
Elist

Reputation: 5533

Peeking deep into Queue

I'm using a BlockingQueue, and want to be able to peek into the next elements in the queue. Queue.peek() gives me the first next element, but I need to go deeper.

Is there a standard way, or should I implement it myself (which includes dealing with thread safety issues)?

Upvotes: 1

Views: 1288

Answers (3)

Kanagavelu Sugumar
Kanagavelu Sugumar

Reputation: 19300

queue.stream().peek(e -> System.out.println(e));

While traversing you can do something on each element, then build your own elements.

    System.out.println(Stream.of("one", "two", "three", "four")
          .filter(e -> e.length() > 3)
          .peek(e -> System.out.println("After Filter: " + e))
          .map(String::toUpperCase)
          .peek(e -> System.out.println("After Mapped value: " + e))
          .collect(Collectors.toList()));


After Filter: three
After Mapping: THREE
After Filter: four
After Mapping: FOUR
[THREE, FOUR]

OR

    Queue<Boolean> qq = new ArrayBlockingQueue<>(10);
    for(Boolean element : qq) {
        System.out.println(element);
    }

Upvotes: 0

RaceBase
RaceBase

Reputation: 18868

Understand the Data Structure you are using and the purpose of it.

You can do the same job by different data structures like [List,Set,Array,Vector,Stack,Queue and so on]. But everyone of them have their own features.

Queue is used for FIFO, where you access elements in the same way, to access next element, first element should be moved out of it.

Upvotes: -1

Shuhail Kadavath
Shuhail Kadavath

Reputation: 448

Use while lopp for this

while ((value=q.poll())!=null)
            System.out.println(value);
    }

Upvotes: -2

Related Questions