Article image

CA

Claudio Andrade01/07/2024 10:30
Compartilhe

Map, Stacks & Collections

    Coleções, Map, Stack: Resumo


    image


    List ↔ Lista

    • Nome: Lista
    • Descrição: É uma coleção ordenada de elementos (índices começam em zero). Permitem duplicata.
    • Implementações incluem ArrayList, LinkedList, Vector e outras.
    • Operações típicas incluem adicionar, remover e acessar itens por índice.

    Set ↔ Conjunto

    • Nome: Conjunto
    • Descrição: É uma coleção de elementos únicos (sem duplicatas). Sem ordem específica.
    • Implementações incluem HashSet, TreeSet (ordenado por chave) e LinkedHashSet (manter a ordem adicionada ou percorrida).
    • Operações típicas incluem adicionar, remover e verificar se um elemento está presente.

    image

    Queue ↔ Fila

    • Nome: Fila
    • Descrição: É uma coleção que segue o princípio First-In-First-Out (FIFO). Permitem duplicata.
    • Implementações incluem LinkedList (implementação padrão) e ArrayDeque.
    • Operações típicas incluem adicionar elementos, remover um elemento (poll), verificar se a fila está vazia, e olhar para o início da fila.

    Deque

    • Nome: Deque
    • Descrição: É uma coleção duplamente encadeada com métodos para adicionar ou remover itens de ambos os lados (à frente e atrás). Permitem duplicata.
    • Implementações incluem ArrayDeque e LinkedList.
    • Operações típicas incluem adicionar elementos, remover um elemento do front (pollFirst), remover um elemento do final (pollLast), verificar se a fila está vazia ou se o tamanho é zero.

    image

    Stack ↔ Pilha

    • Nome: Pilha
    • Descrição: É uma coleção de último em primeiro (LIFO) com métodos para adicionar e remover itens apenas do final (topo). Permitem duplicata.
    • Implementações incluem Stack (implementação padrão usando Vector) e ArrayDeque.
    • Operações típicas incluem adicionar um elemento, remover o topo mais recente (pop), verificar se a pilha está vazia, e olhar para o topo da pilha.

    image

    Map ↔ Mapa

    • Nome: Mapa
    • Descrição: É uma associação de chaves com valores. As chaves são únicas, mas vários valores podem ser associados a uma mesma chave.
    • Implementações incluem HashMap, TreeMap (ordenado por chave) e LinkedHashMap (mantém a ordem adicionada ou percorrida).
    • Operações típicas incluem adicionar pares de chaves-valores, remover pares de chaves-valores, recuperar valores por chave, verificar se uma chave está presente e iterar sobre as chaves ou valores.


    Exemplos:


    1) Lista:


    // Java program to Demonstrate List Interface


    // Importing all utility classes

    import java.util.*;


    // Main class

    // ListDemo class

    class GFG {


    // Main driver method

    public static void main(String[] args)

    {


    // Creating an object of List interface

    // implemented by the ArrayList class

    List<Integer> l1 = new ArrayList<Integer>();


    // Adding elements to object of List interface

    // Custom inputs


    l1.add(0, 1);

    l1.add(1, 2);


    // Print the elements inside the object

    System.out.println(l1);


    // Now creating another object of the List

    // interface implemented ArrayList class

    // Declaring object of integer type

    List<Integer> l2 = new ArrayList<Integer>();


    // Again adding elements to object of List interface

    // Custom inputs

    l2.add(1);

    l2.add(2);

    l2.add(3);


    // Will add list l2 from 1 index

    l1.addAll(1, l2);


    System.out.println(l1);


    // Removes element from index 1

    l1.remove(1);


    // Printing the updated List 1

    System.out.println(l1);


    // Prints element at index 3 in list 1

    // using get() method

    System.out.println(l1.get(3));


    // Replace 0th element with 5

    // in List 1

    l1.set(0, 5);


    // Again printing the updated List 1

    System.out.println(l1);

    }

    }



    // Java Program to Add Elements to a List


    // Importing all utility classes

    import java.util.*;


    // Main class

    class GFG {


    // Main driver method

    public static void main(String args[])

    {

    // Creating an object of List interface,

    // implemented by ArrayList class

    List<String> al = new ArrayList<>();


    // Adding elements to object of List interface

    // Custom elements

    al.add("Geeks");

    al.add("Geeks");

    al.add(1, "For");


    // Print all the elements inside the

    // List interface object

    System.out.println(al);

    }

    }

    ################################################################################

    2) Set


    // Java program Illustrating Set Interface


    // Importing utility classes

    import java.util.*;


    // Main class

    public class GFG {

    // Main driver method

    public static void main(String[] args)

    {

    // Demonstrating Set using HashSet

    // Declaring object of type String

    Set<String> hash_Set = new HashSet<String>();


    // Adding elements to the Set

    // using add() method

    hash_Set.add("Geeks");

    hash_Set.add("For");

    hash_Set.add("Geeks");

    hash_Set.add("Example");

    hash_Set.add("Set");


    // Printing elements of HashSet object

    System.out.println(hash_Set);

    }

    }


    // Java Program Demonstrating Operations on the Set

    // such as Union, Intersection and Difference operations


    // Importing all utility classes

    import java.util.*;


    // Main class

    public class SetExample {

    // Main driver method

    public static void main(String args[])

    {

    // Creating an object of Set class

    // Declaring object of Integer type

    Set<Integer> a = new HashSet<Integer>();

    // Adding all elements to List

    a.addAll(Arrays.asList(

    new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));

    // Again declaring object of Set class

    // with reference to HashSet

    Set<Integer> b = new HashSet<Integer>();

    b.addAll(Arrays.asList(

    new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));


    // To find union

    Set<Integer> union = new HashSet<Integer>(a);

    union.addAll(b);

    System.out.print("Union of the two Set");

    System.out.println(union);


    // To find intersection

    Set<Integer> intersection = new HashSet<Integer>(a);

    intersection.retainAll(b);

    System.out.print("Intersection of the two Set");

    System.out.println(intersection);


    // To find the symmetric difference

    Set<Integer> difference = new HashSet<Integer>(a);

    difference.removeAll(b);

    System.out.print("Difference of the two Set");

    System.out.println(difference);

    }

    }


    ################################################################################


    3) Queue:


    import java.util.LinkedList;

    import java.util.Queue;


    public class QueueExample {

    public static void main(String[] args) {

    Queue<String> queue = new LinkedList<>();


    // add elements to the queue

    queue.add("apple");

    queue.add("banana");

    queue.add("cherry");


    // print the queue

    System.out.println("Queue: " + queue);


    // remove the element at the front of the queue

    String front = queue.remove();

    System.out.println("Removed element: " + front);


    // print the updated queue

    System.out.println("Queue after removal: " + queue);


    // add another element to the queue

    queue.add("date");


    // peek at the element at the front of the queue

    String peeked = queue.peek();

    System.out.println("Peeked element: " + peeked);


    // print the updated queue

    System.out.println("Queue after peek: " + queue);

    }

    }


    // Java program to demonstrate a Queue


    import java.util.LinkedList;

    import java.util.Queue;


    public class QueueExample {


    public static void main(String[] args)

    {

    Queue<Integer> q

    = new LinkedList<>();


    // Adds elements {0, 1, 2, 3, 4} to

    // the queue

    for (int i = 0; i < 5; i++)

    q.add(i);


    // Display contents of the queue.

    System.out.println("Elements of queue "

    + q);


    // To remove the head of queue.

    int removedele = q.remove();

    System.out.println("removed element-"

    + removedele);


    System.out.println(q);


    // To view the head of queue

    int head = q.peek();

    System.out.println("head of queue-"

    + head);


    // Rest all methods of collection

    // interface like size and contains

    // can be used with this

    // implementation.

    int size = q.size();

    System.out.println("Size of queue-"

    + size);

    }

    }


    ################################################################################

    4) Deque



    import java.util.ArrayDeque;

    import java.util.Deque;


    public class Example {

    public static void main(String[] args) {

    Deque<Integer> deque = new ArrayDeque<>();

    deque.addFirst(1);

    deque.addLast(2);

    int first = deque.removeFirst();

    int last = deque.removeLast();

    System.out.println("First: " + first + ", Last: " + last);

    }

    }


    // Java program to demonstrate the working

    // of a Deque in Java


    import java.util.*;


    public class DequeExample {

    public static void main(String[] args)

    {

    Deque<String> deque

    = new LinkedList<String>();


    // We can add elements to the queue

    // in various ways


    // Add at the last

    deque.add("Element 1 (Tail)");


    // Add at the first

    deque.addFirst("Element 2 (Head)");


    // Add at the last

    deque.addLast("Element 3 (Tail)");


    // Add at the first

    deque.push("Element 4 (Head)");


    // Add at the last

    deque.offer("Element 5 (Tail)");


    // Add at the first

    deque.offerFirst("Element 6 (Head)");


    System.out.println(deque + "\n");


    // We can remove the first element

    // or the last element.

    deque.removeFirst();

    deque.removeLast();

    System.out.println("Deque after removing "

    + "first and last: "

    + deque);

    }

    }


    ################################################################################

    5) Stack:


    // Java code for stack implementation


    import java.io.*;

    import java.util.*;


    class Test

    {

    // Pushing element on the top of the stack

    static void stack_push(Stack<Integer> stack)

    {

    for(int i = 0; i < 5; i++)

    {

    stack.push(i);

    }

    }


    // Popping element from the top of the stack

    static void stack_pop(Stack<Integer> stack)

    {

    System.out.println("Pop Operation:");


    for(int i = 0; i < 5; i++)

    {

    Integer y = (Integer) stack.pop();

    System.out.println(y);

    }

    }


    // Displaying element on the top of the stack

    static void stack_peek(Stack<Integer> stack)

    {

    Integer element = (Integer) stack.peek();

    System.out.println("Element on stack top: " + element);

    }


    // Searching element in the stack

    static void stack_search(Stack<Integer> stack, int element)

    {

    Integer pos = (Integer) stack.search(element);


    if(pos == -1)

    System.out.println("Element not found");

    else

    System.out.println("Element is found at position: " + pos);

    }



    public static void main (String[] args)

    {

    Stack<Integer> stack = new Stack<Integer>();


    stack_push(stack);

    stack_pop(stack);

    stack_push(stack);

    stack_peek(stack);

    stack_search(stack, 2);

    stack_search(stack, 6);

    }

    }


    // Java program to add the

    // elements in the stack

    import java.io.*;

    import java.util.*;


    class StackDemo {


    // Main Method

    public static void main(String[] args)

    {


    // Default initialization of Stack

    Stack stack1 = new Stack();


    // Initialization of Stack

    // using Generics

    Stack<String> stack2 = new Stack<String>();


    // pushing the elements

    stack1.push("4");

    stack1.push("All");

    stack1.push("Geeks");


    stack2.push("Geeks");

    stack2.push("For");

    stack2.push("Geeks");


    // Printing the Stack Elements

    System.out.println(stack1);

    System.out.println(stack2);

    }

    }

    ################################################################################


    6) Map:


    // Java Program to Demonstrate

    // Working of Map interface


    // Importing required classes

    import java.util.*;


    // Main class

    class GFG {


    // Main driver method

    public static void main(String args[])

    {

    // Creating an empty HashMap

    Map<String, Integer> hm

    = new HashMap<String, Integer>();


    // Inserting pairs in above Map

    // using put() method

    hm.put("a", new Integer(100));

    hm.put("b", new Integer(200));

    hm.put("c", new Integer(300));

    hm.put("d", new Integer(400));


    // Traversing through Map using for-each loop

    for (Map.Entry<String, Integer> me :

    hm.entrySet()) {


    // Printing keys

    System.out.print(me.getKey() + ":");

    System.out.println(me.getValue());

    }

    }

    }


    // Java Program to illustrate the Hashmap Class


    // Importing required classes

    import java.util.*;


    // Main class

    public class GFG {


    // Main driver method

    public static void main(String[] args)

    {


    // Creating an empty HashMap

    Map<String, Integer> map = new HashMap<>();


    // Inserting entries in the Map

    // using put() method

    map.put("vishal", 10);

    map.put("sachin", 30);

    map.put("vaibhav", 20);


    // Iterating over Map

    for (Map.Entry<String, Integer> e : map.entrySet())


    // Printing key-value pairs

    System.out.println(e.getKey() + " "

    + e.getValue());

    }

    }


    Exemplos de referência:


    https://www.geeksforgeeks.org/collections-in-java-2/


    Mais exemplos:


    https://github.com/claudio-es-andrade/Artigos/Collections

    Compartilhe
    Comentários (0)