Java Set operation

Set does not hold duplicate elements. If you try to add multiple entities of the same object to a Set, it prevents this duplication. The most commonly used Set is the test attribute, where you can easily ask if an object is in a Set. Because of this, lookup is the most important operation in a Set, so you’ll often choose an implementation of HashSet that is optimized for fast lookup.

Set has exactly the same interface as Collection, so it doesn’t have any extra functionality, unlike the previous two different lists. A Set is actually a Collection, but behaves differently. (This is a typical application of the idea of inheritance versus polymorphism: showing different behaviors.) Set attributes are determined based on the value of the object. ,

Here is an example of using a HashSet that holds an Integer object:

package p10;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class SetOfInteger {
    public static void main(String[] args) {
        Random random = new Random(47);
        Set<Integer> integerSet = new HashSet<Integer>();
        for(int i = 0; i <10000; i++){ integerSet.add(random.nextInt(60));
        }
        System.out.println(integerSet);
        / * * * "does not guarantee order" and "disorder" inequitable * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, * 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, * 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, * 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59}}Copy the code

You’ll also notice that the order of the output doesn’t follow any rules, because hashsets use hashes for speed reasons. HashSet maintains a different order than either TreeSet or LinkedHashSet, because their implementations have different ways of storing elements. TreeSet stores elements in red-black tree data structures, whereas HashSet uses hash functions. LinkedHashList also uses hashes for query speed, but it appears to use linked lists to maintain element insertion order.

If you want to sort the results, one way is to use TreeSet instead of HashSet;

package p10;

import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetOfInteger {
    public static void main(String[] args) {
        Random random = new Random(47);
        SortedSet<Integer> integers = new TreeSet<>();
        for(int i = 0; i <10000; i++){ integers.add(random.nextInt(30));
        }
        System.out.println(integers);
        / * * * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, * 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] * /}}Copy the code

One of the most common operations you will perform is to test the attribute of a Set using Contains (), but there are many other operations that will remind you of Venn diagrams taught in elementary school.

package p10;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class SetOperation {
    public static void main(String[] args) {
        Set<String> set1 = new HashSet<>();
        Collections.addAll(set1,"A B C D E F G H I J K L".split(""));
        set1.add("M");
        System.out.println("H: " + set1.contains("H"));
        System.out.println("N: " + set1.contains("N"));
        Set<String> set2 = new HashSet<>();
        Collections.addAll(set2,"H I J K L".split(""));
        System.out.println("set2 in set1: "+set1.containsAll(set2));
        set1.remove("H");
        System.out.println("set1: " + set1);
        System.out.println("set2 in set1: "+set1.containsAll(set2));
        System.out.println("set2: "+ set2);
        set1.remove(set2);
        System.out.println("set2 removed from set1: "+set1);
        Collections.addAll(set1,"X Y Z".split(""));
        System.out.println("'X Y Z' added to set1: " + set1);
        /** * H: true * N: false * set2 in set1: true * set1: [A, B, C, D, E, F, G, I, J, K, L, M] * set2 in set1: false * set2: [H, I, J, K, L] * set2 removed from set1: [A, B, C, D, E, F, G, I, J, K, L, M] * 'X Y Z' added to set1: [A, B, C, D, E, F, G, I, J, K, L, M, X, Y, Z] */}}Copy the code
The Java Queue operation
  1. The average queue

A queue is a typical first-in, first-out (FIFO) container. That is, things are put in one end of the container and taken out the other, and they are put in the same order as they were taken out. Queues are often used as a reliable way to transfer objects from one area of a program to another. Queues are particularly important in concurrent programming.

LinkedList provides methods to support Queue behavior, and it implements the Queue interface, so LinkedList can be used as an implementation of Queue. The following example uses queue-related methods in the Queue interface by upcasting the LinkedList to Queue:

package p10;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;

public class QueueDemo {
    public static void printQ(Queue queue){
        while(queue.peek() ! =null){
            System.out.print(queue.remove() + "");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        Random rand = new Random(47);
        for(int i = 0; i <10; i++){ queue.offer(rand.nextInt(i+10));
        }
        printQ(queue);
        Queue<Character> qc = new LinkedList<>();
        for(char c :"Brontosaurus".toCharArray()){
            qc.offer(c);
        }
        printQ(qc);
        /** * 8 1 1 1 5 14 3 1 0 1 * B r o n t o s a u r u s */}}Copy the code

The offer() method is one of the Queue related methods, which inserts an element at the end of the Queue, if allowed, or returns false. Peek () and elementO both return the queue head without removing it, but the peek() method returns null if the queue is empty and Element () throws a NoSuchElementException. The poll() and remove() methods remove and return the queue head, but poll() returns NULL if the queue is empty, and remove() throws a NoSuchElementException.

The auto-wrapping mechanism automatically converts the int result of the nextInt() method into the Integer object required by queue and the char C into the Character object required by QC. The Queue interface Narrows access to the methods of the LinkedList so that only appropriate methods are available, so there are fewer LinkedList methods that you can access (here you can actually transform the Queue back to the LinkedList, but at least we discourage this).

  1. Priority queue

Fifo describes the most typical queue rules. A queue rule is a rule that determines the next element to pop out of a queue given the elements in a set of queues. Fifo states that the next element should be the one that waits the longest.

The priority queue declares that the next pop-up element is the most needed (with the highest priority). For example, at an airport, when a plane is about to take off, the passengers of that plane can go to the head of the check-in line. If you build a message system where some messages are more important than others and therefore should be processed more quickly, then when they are processed is independent of when they arrive. PriorityQueue was added to Java SE5 to provide an automatic implementation of this behavior.

When you insert an object by calling the offer() method on PriorityQueue, the object will be sorted in the queue. The default sort will use the natural order of objects in the queue, but you can change this order by providing your own Comparator. PriorityQueue ensures that when you call the peek(),poll(), and remove() methods, the element fetched will be the highest priority element in the queue.

Getting PriorityQueue to work with built-in types like Integer, String, and Character is a snap. In the following example, the first set of values is the same as the random values in the previous example, so you can see that they pop out of the PriorityQueue in a different order than in the previous example.

package p10;

import java.util.*;

public class PriorityQueueDemo {
    public static void main(String[] args) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        Random rand = new Random(47);
        for(int i = 0; i <10; i++){ priorityQueue.offer(rand.nextInt(i+10));
        }
        QueueDemo.printQ(priorityQueue);

        List<Integer> ints = Arrays.asList(25.22.20.18.14.9.3.1.1.2.3.9.14.18.21.23.25);
        priorityQueue = new PriorityQueue<>(ints);
        QueueDemo.printQ(priorityQueue);

        priorityQueue = new PriorityQueue<>(ints.size(), Collections.reverseOrder());
        priorityQueue.addAll(ints);
        QueueDemo.printQ(priorityQueue);

        String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
        List<String> strings = Arrays.asList(fact.split(""));
        PriorityQueue<String> stringPQ = new PriorityQueue<>(strings);
        QueueDemo.printQ(stringPQ);

        stringPQ = new PriorityQueue<>(strings.size(),Collections.reverseOrder());
        stringPQ.addAll(strings);
        QueueDemo.printQ(stringPQ);

        Set<Character> characterSet = new HashSet<>();
        for(char c :fact.toCharArray()){
            characterSet.add(c);
        }
        PriorityQueue<Character> characterPQ = new PriorityQueue<>(characterSet);
        QueueDemo.printQ(characterPQ);

        /** * 0 1 1 1 1 1 1 3 5 8 14 * 1 1 23 3 9 9 14 14 18 18 20 21 22 23 25 25 * 25 23 22 21 20 18 18 14 14 9 9 3 3 1  A A B C C C D D E E E F H H I I L N N O O O O S S S T T U U U W * W U U U T T S S S O O O O N N L I I H H F E E E D D C  C C B A A * A B C D E F H I L N O S T U W */}}Copy the code
Deque interface (implementation stack and queue)

Use ArrayDeque to transition up to Deque

      Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.

package p10;

import java.util.ArrayDeque;
import java.util.Deque;

public class DequeDemo {
    public static void printQ(Deque deque){
        while(! deque.isEmpty()){ System.out.print(deque.remove() +"");
        }
        System.out.println();
    }
    public static void printS(Deque deque){
        while(! deque.isEmpty()){ System.out.print(deque.peek() +"");
            deque.pop();
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Deque<Integer> queue = new ArrayDeque<>();
        for(int i= 0; i <10; i++){ queue.add(i); } printQ(queue); Deque<Integer> stack =new ArrayDeque<>();
        for(int i = 0; i <10; i++){ stack.push(i); } printS(stack);/** * 0 1 2 3 4 5 6 7 9 */}}Copy the code