DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

1

Queue<E> (para filas e processamento por ordem)

Queue (para filas e processamento por ordem)
Implementações principais: LinkedList (como fila), PriorityQueue
Motivo: Usada em operações onde a ordem de processamento é importante.

1. O que é Queue?

  • Interface da Java Collections Framework.
  • Representa uma estrutura de dados do tipo fila (FIFO – First In, First Out).
  • Utilizada para processar elementos na ordem em que foram inseridos.

2. Implementações principais

  • 2.1. LinkedList como Queue
  • A classe LinkedList implementa a interface Queue.
  • Pode ser usada como uma fila comum (FIFO).

Exemplo:

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<String> fila = new LinkedList<>();

        // Adicionando elementos à fila
        fila.add("A");
        fila.add("B");
        fila.add("C");


        System.out.println("Valores da Fila: "); // [A, B, C]
        fila.forEach(value -> System.out.println(" " + value));


        // Removendo elementos na ordem de chegada (FIFO)
        System.out.println("Removido: " + fila.poll()); // A
        System.out.println("Nova fila: " + fila); // [B, C]
    }
}

Enter fullscreen mode Exit fullscreen mode

2.2. PriorityQueue

  • Não garante ordem FIFO, mas ordena os elementos conforme prioridade.
  • Utilizada quando a ordem de processamento depende da prioridade dos elementos.
import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> filaPrioridade = new PriorityQueue<>();

        filaPrioridade.add(30);
        filaPrioridade.add(10);
        filaPrioridade.add(20);

        System.out.println("Fila de prioridade: " + filaPrioridade); // A ordem pode não ser óbvia

        // Removendo elementos na ordem de prioridade (menor primeiro)
        System.out.println("Removido: " + filaPrioridade.poll()); // 10
        System.out.println("Removido: " + filaPrioridade.poll()); // 20
        System.out.println("Removido: " + filaPrioridade.poll()); // 30
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Métodos principais de Queue

Image description

4. Quando usar Queue?

  • Processamento de tarefas: Exemplo, filas de impressão, filas de pedidos.
  • Sistemas de mensagens: Exemplo, mensagens de chat processadas na ordem de chegada.
  • Algoritmos de busca: Exemplo, BFS (Busca em Largura) em grafos.
  • Eventos em jogos: Exemplo, fila de eventos em jogos multiplayer.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay