Java

Java – Collections With Example Programs

A group of classes and interfaces known as the Java Collections Framework aid in the effective storage and handling of data. This framework offers a number of beneficial classes with a ton of beneficial features, which makes a programmer’s job really simple. I’ve produced a number of Java lessons on collections. For your benefit, the instructions are all supplied with examples and source codes.

Collections Framework hierarchy

Java - Collections With Example Programs

1. List

An ordered Collection is a list (sometimes called a sequence). Duplicate items are possible in lists. A zero-based index may be used to insert or access elements according to their position in the list. The following classes implement the List interface:

  • ArrayList
  • LinkedList
  • Vector
  • Stack

1.1 ArrayList

In Java, ArrayList is a well-liked array substitute. The Array data structure serves as its foundation. A resizable-array implementation of the List interface is called ArrayList. It supports all items, including null, and provides all optional list operations. To study ArrayList in depth, go to this manual.

import java.util.*;
class JavaExample{
  public static void main(String args[]){
    //creating ArrayList of string type
    ArrayList<String> arrList=new ArrayList<>();

    //adding few elements
    arrList.add("Cricket"); //list: ["Cricket"]
    arrList.add("Hockey"); //list: ["Cricket", "Hockey"]

    //inserting element at first position, index 0
    //represents first element because ArrayList is based
    //on zero based indexing system
    arrList.add(0, "BasketBall"); //list: ["BasketBall", "Cricket", "Hockey"]


    System.out.println("ArrayList Elements: ");
    //Traversing ArrayList using enhanced for loop
    for(String str:arrList)
      System.out.println(str);
  }
}

Output:
Collections in Java ArrayList

1.2 LinkedList

A linear data structure is LinkedList. However, unlike arrays, LinkedList components are connected to one another through pointers rather than being stored in consecutive places. Each entry of a linked list has a reference (or address or pointer) to the element after it.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    LinkedList<String> linkList=new LinkedList<>();
    linkList.add("Apple"); //["Apple"]
    linkList.add("Orange"); //["Apple", "Orange"]

    //inserting element at first position
    linkList.add(0, "Banana"); ////["Banana", "Apple", "Orange"]

    System.out.println("LinkedList elements: ");
    //iterating LinkedList using iterator
    Iterator<String> it=linkList.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

Output:
Java - Collections With Example Programs

1.3 Vector

Here is a list of all tutorials that have been released for the Vector.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    Vector<String> v=new Vector<>();
    v.add("item1"); //["item1"]
    v.add("item2"); //["item1", "item2"]
    v.add("item3"); //["item1", "item2", "item3"]

    //removing an element
    v.remove("item2"); //["item1", "item3"]

    System.out.println("Vector Elements: ");
    //iterating Vector using iterator
    Iterator<String> it=v.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

Output:
Java - Collections With Example Programs

1.4 Stack

Stack class is a subclass of Vector since it extends the latter. Stack operates using the Last In First Out principle (LIFO). The items are added to the stack using the push() function, while the pop() method removes the element that was added last.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    Stack<String> stack = new Stack<>();

    //push() method adds the element in the stack
    //and pop() method removes the element from the stack
    stack.push("Chaitanya"); //["Chaitanya"]
    stack.push("Ajeet"); //["Chaitanya", Ajeet]
    stack.push("Hari"); //["Chaitanya", "Ajeet", "Hari"]
    stack.pop(); //removes the last element
    stack.push("Steve"); //["Chaitanya", "Ajeet", "Steve"]
    stack.push("Carl"); //["Chaitanya", "Ajeet", "Steve", "Carl"]
    stack.pop(); //removes the last element

    System.out.println("Stack elements: ");
    for(String str: stack){
      System.out.println(str);
    }
  }
}

Output:
Java - Collections With Example Programs

2. Set

A Collection that excludes duplicate pieces is referred to as a Set. HashSet, TreeSet, and LinkedHashSet are the major implementations of the Set interface.

2.1 HashSet

The best-performing solution is HashSet, which keeps its items in a hash table. HashSet only permits distinct items. Since the insertion order is not maintained, an element that was put last may appear first while traversing the hash set.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashSet<String> set=new HashSet<>();
    set.add("Paul");
    set.add("Ram");
    set.add("Aaron");
    set.add("Leo");
    set.add("Becky");

    Iterator<String> it=set.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

Output:

Aaron
Leo
Paul
Ram
Becky

2.2 LinkedHashSet

The LinkedHashSet preserves insertion order in contrast to HashSet.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    LinkedHashSet<String> set=new LinkedHashSet<>();
    set.add("Paul");
    set.add("Ram");
    set.add("Aaron");
    set.add("Leo");
    set.add("Becky");

    Iterator<String> it=set.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

Output:

Paul
Ram
Aaron
Leo
Becky

2.3 TreeSet

Red-black trees are used by TreeSet to store items. It moves much more slowly than HashSet. The TreeSet class implements the SortedSet interface, enabling TreeSet to sort its components in ascending order depending on the values assigned to them.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    TreeSet<String> set=new TreeSet<>();
    set.add("Paul");
    set.add("Ram");
    set.add("Aaron");
    set.add("Leo");
    set.add("Becky");

    Iterator<String> it=set.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

Output:

Aaron
Becky
Leo
Paul
Ram

3. Map

A map is an object that associates values with keys. There can be only one set of keys on a map. HashMap, TreeMap, and LinkedHashMap are the three primary Map interface implementations.

3.1 HashMap

Similar to HashSet, HashMap does not preserve insertion order and does not organize the entries. To study HashMap in full, go to this manual.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashMap<Integer, String> hmap = new HashMap<>();

    //key and value pairs
    hmap.put(101, "Chaitanya");
    hmap.put(105, "Derick");
    hmap.put(111, "Logan");
    hmap.put(120, "Paul");

    //print HashMap elements
    Set set = hmap.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
      Map.Entry m = (Map.Entry)iterator.next();
      System.out.print("key is: "+ m.getKey() + " & Value is: ");
      System.out.println(m.getValue());
    }
  }
}

Output:
Java - Collections With Example Programs

3.2 TreeMap

TreeMap: It uses a red-to-black tree to store its components. In TreeMap, the components are arranged in ascending order. It moves much more slowly than HashMap. To learn TreeMap with examples, go to this manual.

This is the same HashMap example that we saw before. In this case, keys are used to sort the items.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    TreeMap<Integer, String> hmap = new TreeMap<>();

    //key and value pairs
    hmap.put(101, "Chaitanya");
    hmap.put(105, "Derick");
    hmap.put(111, "Logan");
    hmap.put(120, "Paul");

    //print HashMap elements
    Set set = hmap.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
      Map.Entry m = (Map.Entry)iterator.next();
      System.out.print("key is: "+ m.getKey() + " & Value is: ");
      System.out.println(m.getValue());
    }
  }
}

Output:
Java - Collections With Example Programs

3.3 LinkedHashMap

The LinkedHashMap preserves insertion order. To study LinkedHashMap in depth, go to this manual. You may observe that: The key and value pairs in the next example kept their insertion order.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    LinkedHashMap<Integer, String> hmap = new LinkedHashMap<>();

    //key and value pairs
    hmap.put(100, "Chaitanya");
    hmap.put(120, "Paul");
    hmap.put(105, "Derick");
    hmap.put(111, "Logan");

    //print LinkedHashMap elements
    Set set = hmap.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
      Map.Entry m = (Map.Entry)iterator.next();
      System.out.print("key is: "+ m.getKey() + " & Value is: ");
      System.out.println(m.getValue());
    }
  }
}

Output:

key is: 100 & Value is: Chaitanya
key is: 120 & Value is: Paul
key is: 105 & Value is: Derick
key is: 111 & Value is: Logan

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button