Difference between revisions of "JAVA: Collection di Java"

From OnnoWiki
Jump to navigation Jump to search
Line 91: Line 91:
  
 
{| class="wikitable"
 
{| class="wikitable"
|+ Caption text
+
|+ Method dari Collection Interface
 
|-
 
|-
 
! Method !! Description
 
! Method !! Description

Revision as of 09:34, 25 May 2022

Setiap kelompok object individu yang direpresentasikan sebagai satu unit dikenal sebagai collection object. Di Java, framework terpisah bernama "Collection Framework" telah didefinisikan di JDK 1.2 yang menampung semua collection class dan interface di dalamnya.

Interface Collection (java.util.Collection) dan Interface Map (java.util.Map) adalah dua interface main "root" dari Java collection class.


Apakah Framework?

Framework adalah seperangkat class dan interface yang menyediakan arsitektur siap pakai. Untuk mengimplementasikan fitur atau class baru, tidak perlu mendefinisikan framework. Namun, desain object-oriented yang optimal selalu menyertakan framework dengan kumpulan class sedemikian rupa sehingga semua class melakukan jenis tugas yang sama.


Kebutuhan untuk Collection Framework berbeda

Sebelum Collection Framework (atau sebelum JDK 1.2) diperkenalkan, method standar untuk mengelompokkan object Java (atau collection) adalah Array atau Vektor, atau Hashtable. Semua collection tidak memiliki interface yang sama. Oleh karena itu, meskipun tujuan utama dari semua collection adalah sama, implementasi dari semua collection ini didefinisikan secara independen dan tidak ada korelasi di antara mereka. Dan juga, sangat sulit bagi pengguna untuk mengingat semua method, sintaks, dan konstruktor berbeda yang ada di setiap collection class.

Untuk memahami ini melalui contoh menambahkan elemen dalam tabel hash dan vektor.


// Java program to demonstrate
// why collection framework was needed
import java.io.*;
import java.util.*;
 
class CollectionDemo {
  
    public static void main(String[] args)
    {
        // Creating instances of the array,
        // vector and hashtable
        int arr[] = new int[] { 1, 2, 3, 4 };
        Vector<Integer> v = new Vector();
        Hashtable<Integer, String> h = new Hashtable();
  
        // Adding the elements into the
        // vector
        v.addElement(1);
        v.addElement(2);
  
        // Adding the element into the
        // hashtable
        h.put(1, "geeks");
        h.put(2, "4geeks");
  
        // Array instance creation requires [],
        // while Vector and hastable require ()
        // Vector element insertion requires addElement(),
        // but hashtable element insertion requires put()
  
        // Accessing the first element of the
        // array, vector and hashtable
        System.out.println(arr[0]);
        System.out.println(v.elementAt(0));
        System.out.println(h.get(1));
  
        // Array elements are accessed using [],
        // vector elements using elementAt()
        // and hashtable elements using get()
    }
}

Output:

1
1
geeks

Seperti yang dapat kita amati, tidak satu pun dari collection ini (Array, Vektor, atau Hashtable) yang mengimplementasikan interface akses anggota standar, sangat sulit bagi pemrogram untuk menulis algoritma yang dapat bekerja untuk semua jenis collection. Kelemahan lainnya adalah sebagian besar method 'Vector' bersifat final, yang berarti kita tidak dapat memperluas class 'Vector' untuk mengimplementasikan jenis collection yang serupa. Oleh karena itu, pengembang Java memutuskan untuk membuat interface umum untuk menangani masalah yang disebutkan di atas dan memperkenalkan Framework Collection di posting JDK 1.2 yang keduanya, Vektor legacy dan Tabel Hash dimodifikasi agar sesuai dengan Collection Framework.


Keuntungan dari Collection Framework:

Karena kurangnya collection framework menimbulkan serangkaian kerugian di atas, berikut ini adalah keuntungan dari collection framework.

  • API yang Konsisten: API memiliki seperangkat interface dasar seperti Collection, Set, List, or Map,, semua Class (ArrayList, LinkedList, Vector, dll) yang mengimplementasikan interface ini memiliki beberapa set method yang umum.
  • Mengurangi upaya pemrograman: Seorang programmer tidak perlu khawatir tentang desain Collection tetapi ia dapat fokus pada penggunaan terbaiknya dalam programnya. Oleh karena itu, konsep dasar Object-oriented programming (yaitu) abstraksi telah berhasil diimplementasikan.
  • Meningkatkan kecepatan dan kualitas program: Meningkatkan kinerja dengan menyediakan implementasi kinerja tinggi dari struktur data dan algoritma yang berguna karena dalam hal ini, programmer tidak perlu memikirkan implementasi terbaik dari struktur data tertentu. Dia dapat dengan mudah menggunakan implementasi terbaik untuk secara drastis meningkatkan kinerja algoritma/programnya.

Hierarki dari Collection Framework

Paket utilitas, (java.util) berisi semua class dan interface yang diperlukan oleh collection framework. Collection framework berisi interface bernama iterable interface yang menyediakan iterator untuk melakukan iterasi melalui semua collection. Interface ini diperluas oleh interface main collection yang bertindak sebagai root untuk kerangka collection framework. Semua collection memperluas interface collection ini sehingga memperluas properti iterator dan method dari interface. Gambar berikut mengilustrasikan hierarki collection framework.

Collection-Framework-Hierarchy

Sebelum memahami berbagai komponen dalam framework di atas, mari kita pahami dulu class dan interface

  • Class: Sebuah Class adalah cetak biru atau prototipe yang ditentukan user dari mana object dibuat. Ini mewakili set properti atau method yang umum untuk semua objek dari satu jenis.
  • Interface: Seperti Class, interface dapat memiliki method dan variabel, tetapi method yang dideklarasikan dalam interface secara default abstrak (hanya method signature, tanpa body). Interface menentukan apa yang harus dilakukan class dan bukan bagaimana caranya. Ini adalah cetak biru class.

Method dari Collection Interface

Interface ini berisi berbagai method yang dapat langsung digunakan oleh semua collection yang mengimplementasikan interface tersebut. Mereka adalah:

Method dari Collection Interface
Method Description
add(Object) This method is used to add an object to the collection.
addAll(Collection c) This method adds all the elements in the given collection to this collection.
clear() This method removes all of the elements from this collection.
contains(Object o) This method returns true if the collection contains the specified element.
containsAll(Collection c) This method returns true if the collection contains all of the elements in the given collection.
equals(Object o) This method compares the specified object with this collection for equality.
hashCode() This method is used to return the hash code value for this collection.
isEmpty() This method returns true if this collection contains no elements.
iterator() This method returns an iterator over the elements in this collection.
max() This method is used to return the maximum value present in the collection.
parallelStream() This method returns a parallel Stream with this collection as its source.
remove(Object o) This method is used to remove the given object from the collection. If there are duplicate values, then this method removes the first occurrence of the object.
removeAll(Collection c) This method is used to remove all the objects mentioned in the given collection from the collection.
removeIf(Predicate filter) This method is used to remove all the elements of this collection that satisfy the given predicate.
retainAll(Collection c) This method is used to retain only the elements in this collection that are contained in the specified collection.
size() This method is used to return the number of elements in the collection.
spliterator() This method is used to create a Spliterator over the elements in this collection.
stream() This method is used to return a sequential Stream with this collection as its source.
toArray() This method is used to return an array containing all of the elements in this collection.

Interfaces that extend the Collections Interface

The collection framework contains multiple interfaces where every interface is used to store a specific type of data. The following are the interfaces present in the framework.

Kerangka pengumpulan berisi beberapa antarmuka di mana setiap antarmuka digunakan untuk menyimpan jenis data tertentu. Berikut ini adalah antarmuka yang ada dalam kerangka kerja.


1. Iterable Interface:

This is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the

Ini adalah antarmuka root untuk seluruh kerangka koleksi. Antarmuka koleksi memperluas antarmuka yang dapat diubah. Oleh karena itu, secara inheren, semua antarmuka dan kelas mengimplementasikan antarmuka ini. Fungsi utama antarmuka ini adalah menyediakan iterator untuk koleksi. Oleh karena itu, antarmuka ini hanya berisi satu metode abstrak yang merupakan iterator. Ini mengembalikan


Iterator iterator(); 

2. Collection Interface:

This interface extends the iterable interface and is implemented by all the classes in the collection framework. This interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation. And also, having these methods in this interface ensures that the names of the methods are universal for all the collections. Therefore, in short, we can say that this interface builds a foundation on which the collection classes are implemented.


Antarmuka ini memperluas antarmuka yang dapat diubah dan diimplementasikan oleh semua kelas dalam kerangka koleksi. Antarmuka ini berisi semua metode dasar yang dimiliki setiap koleksi seperti menambahkan data ke dalam koleksi, menghapus data, menghapus data, dll. Semua metode ini diimplementasikan dalam antarmuka ini karena metode ini diimplementasikan oleh semua kelas terlepas dari gayanya implementasi. Dan juga, memiliki metode ini di antarmuka ini memastikan bahwa nama metode bersifat universal untuk semua koleksi. Oleh karena itu, singkatnya, kita dapat mengatakan bahwa antarmuka ini membangun fondasi di mana kelas koleksi diimplementasikan.

3. List Interface:

This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example,

Ini adalah antarmuka anak dari antarmuka koleksi. Antarmuka ini didedikasikan untuk data tipe daftar di mana kita dapat menyimpan semua koleksi objek yang dipesan. Ini juga memungkinkan data duplikat hadir di dalamnya. Antarmuka daftar ini diimplementasikan oleh berbagai kelas seperti ArrayList, Vektor, Stack, dll. Karena semua subkelas mengimplementasikan daftar, kita dapat membuat instance objek daftar dengan salah satu dari kelas-kelas ini. Sebagai contoh,


List <T> al = new ArrayList<> (); 
List <T> ll = new LinkedList<> (); 
List <T> v = new Vector<> (); 

Where T is the type of the object

The classes which implement the List interface are as follows:


Dimana T adalah jenis benda

Kelas-kelas yang mengimplementasikan antarmuka Daftar adalah sebagai berikut:

A. ArrayList:

ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc. We will need a wrapper class for such cases. Let’s understand the ArrayList with the following example:


ArrayList memberi kita array dinamis di Java. Meskipun, mungkin lebih lambat dari array standar tetapi dapat membantu dalam program di mana banyak manipulasi dalam array diperlukan. Ukuran ArrayList meningkat secara otomatis jika koleksi bertambah atau menyusut jika objek dihapus dari koleksi. Java ArrayList memungkinkan kita untuk mengakses daftar secara acak. ArrayList tidak dapat digunakan untuk tipe primitif, seperti int, char, dll. Kita akan membutuhkan kelas pembungkus untuk kasus seperti itu. Mari kita pahami ArrayList dengan contoh berikut:

// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the ArrayList with
        // initial size n
        ArrayList<Integer> al = new ArrayList<Integer>();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            al.add(i);
  
        // Printing elements
        System.out.println(al);
  
        // Remove element at index 3
        al.remove(3);
  
        // Displaying the ArrayList
        // after deletion
        System.out.println(al);
  
        // Printing elements one by one
        for (int i = 0; i < al.size(); i++)
            System.out.print(al.get(i) + " ");
    }
}

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

B. LinkedList:

LinkedList class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Let’s understand the LinkedList with the following example:


Kelas LinkedList adalah implementasi dari struktur data LinkedList yang merupakan struktur data linier di mana elemen tidak disimpan di lokasi yang berdekatan dan setiap elemen adalah objek terpisah dengan bagian data dan bagian alamat. Elemen-elemen tersebut dihubungkan menggunakan pointer dan alamat. Setiap elemen dikenal sebagai simpul. Mari kita pahami LinkedList dengan contoh berikut:


// Java program to demonstrate the
// working of LinkedList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the LinkedList
        LinkedList<Integer> ll = new LinkedList<Integer>();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            ll.add(i);
  
        // Printing elements
        System.out.println(ll);
  
        // Remove element at index 3
        ll.remove(3);
  
        // Displaying the List
        // after deletion
        System.out.println(ll);
  
        // Printing elements one by one
        for (int i = 0; i < ll.size(); i++)
            System.out.print(ll.get(i) + " ");
    }
}

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

C. Vector:

A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This is identical to ArrayList in terms of implementation. However, the primary difference between a vector and an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized. Let’s understand the Vector with an example:


Sebuah vektor memberi kita array dinamis di Jawa. Meskipun, mungkin lebih lambat dari array standar tetapi dapat membantu dalam program di mana banyak manipulasi dalam array diperlukan. Ini identik dengan ArrayList dalam hal implementasi. Namun, perbedaan utama antara vektor dan ArrayList adalah bahwa Vektor disinkronkan dan ArrayList tidak disinkronkan. Mari kita pahami Vektor dengan sebuah contoh:


// Java program to demonstrate the
// working of Vector
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the Vector
        Vector<Integer> v = new Vector<Integer>();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            v.add(i);
  
        // Printing elements
        System.out.println(v);
  
        // Remove element at index 3
        v.remove(3);
  
        // Displaying the Vector
        // after deletion
        System.out.println(v);
  
        // Printing elements one by one
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

D. Stack:

Stack class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be referred to as the subclass of Vector. Let’s understand the stack with an example:

Model kelas Stack dan mengimplementasikan struktur data Stack. Kelas didasarkan pada prinsip dasar last-in-first-out. Selain operasi push dan pop dasar, kelas ini menyediakan tiga fungsi kosong, pencarian, dan intip. Kelas juga dapat disebut sebagai subkelas dari Vektor. Mari kita pahami stack dengan sebuah contoh:


// Java program to demonstrate the
// working of a stack
import java.util.*;
public class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        Stack<String> stack = new Stack<String>();
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");
        stack.push("Geeks");
  
        // Iterator for the stack
        Iterator<String> itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
  
        System.out.println();
  
        stack.pop();
  
        // Iterator for the stack
        itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
    }
}

Output:

Geeks For Geeks Geeks 
Geeks For Geeks

Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead in an environment where thread safety is not needed. An alternate to Stack is to use ArrayDequeue which is not thread-safe and has faster array implementation.

Nota: Stack es una subclase de Vector y una clase heredada. Es seguro para subprocesos, lo que podría ser una sobrecarga en un entorno donde no se necesita la seguridad de subprocesos. Una alternativa a Stack es usar ArrayDequeue, que no es seguro para subprocesos y tiene una implementación de matriz más rápida.

4. Queue Interface:

As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes. For example,


Seperti namanya, antarmuka antrian mempertahankan urutan FIFO (First In First Out) yang mirip dengan garis antrian dunia nyata. Antarmuka ini didedikasikan untuk menyimpan semua elemen di mana urutan elemen penting. Misalnya, setiap kali kami mencoba memesan tiket, tiket dijual berdasarkan urutan kedatangan. Oleh karena itu, orang yang permintaannya datang lebih dulu ke dalam antrian mendapat tiket. Ada berbagai kelas seperti PriorityQueue, ArrayDeque, dll. Karena semua subkelas ini mengimplementasikan antrian, kita dapat membuat instance objek antrian dengan salah satu dari kelas-kelas ini. Sebagai contoh,


Queue <T> pq = new PriorityQueue<> (); 
Queue <T> ad = new ArrayDeque<> (); 

Where T is the type of the object.

The most frequently used implementation of the queue interface is the PriorityQueue.


Dimana T adalah jenis objek.

Implementasi antarmuka antrian yang paling sering digunakan adalah PriorityQueue.

Priority Queue:

A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority and this class is used in these cases. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. Let’s understand the priority queue with an example:

PriorityQueue digunakan ketika objek seharusnya diproses berdasarkan prioritas. Diketahui bahwa suatu antrian mengikuti algoritma First-In-First-Out, tetapi terkadang elemen-elemen antrian diperlukan untuk diproses sesuai dengan prioritasnya dan kelas ini digunakan dalam kasus ini. PriorityQueue didasarkan pada tumpukan prioritas. Elemen-elemen antrian prioritas diurutkan menurut urutan alami, atau oleh Pembanding yang disediakan pada waktu konstruksi antrian, tergantung pada konstruktor yang digunakan. Mari kita pahami antrian prioritas dengan sebuah contoh:


// Java program to demonstrate the working of
// priority queue in Java
import java.util.*;
  
class GfG {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
  
        // Adding items to the pQueue using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
  
        // Printing the top element of PriorityQueue
        System.out.println(pQueue.peek());
  
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
  
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}

Output:

10
10
15

5. Deque Interface:

This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since ArrayDeque class implements the Deque interface, we can instantiate a deque object with this class. For example,

Ini adalah variasi yang sangat kecil dari struktur data antrian. Deque, juga dikenal sebagai antrian berujung ganda, adalah struktur data tempat kita dapat menambah dan menghapus elemen dari kedua ujung antrian. Antarmuka ini memperluas antarmuka antrian. Kelas yang mengimplementasikan antarmuka ini adalah ArrayDeque. Karena kelas ArrayDeque mengimplementasikan antarmuka Deque, kita dapat membuat instance objek deque dengan kelas ini. Sebagai contoh,


Deque<T> ad = new ArrayDeque<> (); 

Where T is the type of the object.

The class which implements the deque interface is ArrayDeque.

Dimana T adalah jenis objek.

Kelas yang mengimplementasikan antarmuka deque adalah ArrayDeque.


ArrayDeque:

ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. Array deques have no capacity restrictions and they grow as necessary to support usage. Let’s understand ArrayDeque with an example:


Kelas ArrayDeque yang diimplementasikan dalam kerangka koleksi memberi kita cara untuk menerapkan array yang dapat diubah ukurannya. Ini adalah jenis array khusus yang tumbuh dan memungkinkan pengguna untuk menambah atau menghapus elemen dari kedua sisi antrian. Array deques tidak memiliki batasan kapasitas dan mereka tumbuh sesuai kebutuhan untuk mendukung penggunaan. Mari kita pahami ArrayDeque dengan sebuah contoh:


// Java program to demonstrate the
// ArrayDeque class in Java
  
import java.util.*;
public class ArrayDequeDemo {
    public static void main(String[] args)
    {
        // Initializing an deque
        ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10);
   
        // add() method to insert
        de_que.add(10);
        de_que.add(20);
        de_que.add(30);
        de_que.add(40);
        de_que.add(50);
  
        System.out.println(de_que);
  
        // clear() method
        de_que.clear();
  
        // addFirst() method to insert the
        // elements at the head
        de_que.addFirst(564);
        de_que.addFirst(291);
  
        // addLast() method to insert the
        // elements at the tail
        de_que.addLast(24);
        de_que.addLast(14);
  
        System.out.println(de_que);
    }
}

Output:

[10, 20, 30, 40, 50]
[291, 564, 24, 14]

6. Set Interface:

A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is used when we wish to avoid the duplication of the objects and wish to store only the unique objects. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object with any of these classes. For example,

Himpunan adalah kumpulan objek yang tidak berurutan di mana nilai duplikat tidak dapat disimpan. Koleksi ini digunakan ketika kita ingin menghindari duplikasi objek dan ingin menyimpan hanya objek unik. Antarmuka set ini diimplementasikan oleh berbagai kelas seperti HashSet, TreeSet, LinkedHashSet, dll. Karena semua subclass mengimplementasikan set, kita dapat membuat instance objek set dengan salah satu dari kelas-kelas ini. Sebagai contoh,


Set<T> hs = new HashSet<> (); 
Set<T> lhs = new LinkedHashSet<> (); 
Set<T> ts = new TreeSet<> (); 

Where T is the type of the object.

The following are the classes that implement the Set interface:


Dimana T adalah jenis objek.

Berikut ini adalah kelas-kelas yang mengimplementasikan antarmuka Set:

A. HashSet:

The HashSet class is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s understand HashSet with an example:

Kelas HashSet adalah implementasi yang melekat dari struktur data tabel hash. Objek yang kita masukkan ke dalam HashSet tidak menjamin untuk dimasukkan dalam urutan yang sama. Objek dimasukkan berdasarkan kode hashnya. Kelas ini juga memungkinkan penyisipan elemen NULL. Mari kita pahami HashSet dengan sebuah contoh:


// Java program to demonstrate the
// working of a HashSet
import java.util.*;
  
public class HashSetDemo {
    
    // Main Method
    public static void main(String args[])
    {
        // Creating HashSet and
        // adding elements
        HashSet<String> hs = new HashSet<String>();
   
        hs.add("Geeks");
        hs.add("For");
        hs.add("Geeks");
        hs.add("Is");
        hs.add("Very helpful");
  
        // Traversing elements
        Iterator<String> itr = hs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Output:

Very helpful
Geeks
For
Is

B. LinkedHashSet:

A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store the data and retains the ordering of the elements. Let’s understand the LinkedHashSet with an example:

LinkedHashSet sangat mirip dengan HashSet. Perbedaannya adalah bahwa ini menggunakan daftar tertaut ganda untuk menyimpan data dan mempertahankan urutan elemen. Mari kita pahami LinkedHashSet dengan sebuah contoh:


// Java program to demonstrate the
// working of a LinkedHashSet
import java.util.*;
  
public class LinkedHashSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating LinkedHashSet and
        // adding elements
        LinkedHashSet<String> lhs = new LinkedHashSet<String>();
  
        lhs.add("Geeks");
        lhs.add("For");
        lhs.add("Geeks");
        lhs.add("Is");
        lhs.add("Very helpful");
  
        // Traversing elements
        Iterator<String> itr = lhs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Output:

Geeks
For
Is
Very helpful

7. Sorted Set Interface:

This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements. The sorted set interface extends the set interface and is used to handle the data which needs to be sorted. The class which implements this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For example,

Antarmuka ini sangat mirip dengan antarmuka yang ditetapkan. Satu-satunya perbedaan adalah bahwa antarmuka ini memiliki metode tambahan yang mempertahankan urutan elemen. Antarmuka set yang diurutkan memperluas antarmuka set dan digunakan untuk menangani data yang perlu diurutkan. Kelas yang mengimplementasikan antarmuka ini adalah TreeSet. Karena kelas ini mengimplementasikan SortedSet, kita dapat membuat instance objek SortedSet dengan kelas ini. Sebagai contoh,


SortedSet<T> ts = new TreeSet<> (); 

Where T is the type of the object.

The class which implements the sorted set interface is TreeSet.

Dimana T adalah jenis objek.

Kelas yang mengimplementasikan antarmuka set yang diurutkan adalah TreeSet.


TreeSet:

The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. Let’s understand TreeSet with an example:

Kelas TreeSet menggunakan Pohon untuk penyimpanan. Pengurutan elemen dipertahankan oleh suatu himpunan menggunakan pengurutan alaminya terlepas dari apakah komparator eksplisit disediakan atau tidak. Ini harus konsisten dengan equals jika ingin mengimplementasikan antarmuka Set dengan benar. Itu juga dapat dipesan oleh Pembanding yang disediakan pada waktu pembuatan yang ditentukan, tergantung pada konstruktor mana yang digunakan. Mari kita pahami TreeSet dengan sebuah contoh:


// Java program to demonstrate the
// working of a TreeSet
import java.util.*;
  
public class TreeSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating TreeSet and
        // adding elements
        TreeSet<String> ts = new TreeSet<String>();
  
        ts.add("Geeks");
        ts.add("For");
        ts.add("Geeks");
        ts.add("Is");
        ts.add("Very helpful");
  
        // Traversing elements
        Iterator<String> itr = ts.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Output:

For
Geeks
Is
Very helpful

8. Map Interface:

A map is a data structure that supports the key-value pair mapping for the data. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings. A map is useful if there is data and we wish to perform operations on the basis of the key. This map interface is implemented by various classes like HashMap, TreeMap, etc. Since all the subclasses implement the map, we can instantiate a map object with any of these classes. For example,


Peta adalah struktur data yang mendukung pemetaan pasangan nilai kunci untuk data tersebut. Antarmuka ini tidak mendukung kunci duplikat karena kunci yang sama tidak dapat memiliki banyak pemetaan. Peta berguna jika ada data dan kami ingin melakukan operasi berdasarkan kunci. Antarmuka peta ini diimplementasikan oleh berbagai kelas seperti HashMap, TreeMap, dll. Karena semua subkelas mengimplementasikan peta, kita dapat membuat instance objek peta dengan salah satu dari kelas-kelas ini. Sebagai contoh,


Map<T> hm = new HashMap<> (); 
Map<T> tm = new TreeMap<> ();

Where T is the type of the object.

The frequently used implementation of a Map interface is a HashMap.

Dimana T adalah jenis objek.

Implementasi antarmuka Peta yang sering digunakan adalah HashMap.


HashMap:

HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String so that the indexing and search operations are faster. HashSet also uses HashMap internally. Let’s understand the HashMap with an example:

HashMap menyediakan implementasi dasar dari antarmuka Map Java. Ini menyimpan data dalam pasangan (Kunci, Nilai). Untuk mengakses nilai dalam HashMap, kita harus mengetahui kuncinya. HashMap menggunakan teknik yang disebut Hashing. Hashing adalah teknik mengubah String besar menjadi String kecil yang mewakili String yang sama sehingga operasi pengindeksan dan pencarian lebih cepat. HashSet juga menggunakan HashMap secara internal. Mari kita pahami HashMap dengan sebuah contoh:


// Java program to demonstrate the
// working of a HashMap
import java.util.*;
  
public class HashMapDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating HashMap and
        // adding elements
        HashMap<Integer, String> hm = new HashMap<Integer, String> ();
 
        hm.put(1, "Geeks");
        hm.put(2, "For");
        hm.put(3, "Geeks");
  
        // Finding the value for a key
        System.out.println("Value for 1 is " + hm.get(1));
  
        // Traversing through the HashMap
        for (Map.Entry<Integer, String> e : hm.entrySet())
            System.out.println(e.getKey() + " " + e.getValue());
    }
}

Output:

Value for 1 is Geeks
1 Geeks
2 For
3 Geeks

Referensi