UpdateGadh

UPDATEGADH.COM

Java Collection

Welcome to Day 11 of our Java Collection journey! Today, we’ll delve into one of the most fundamental aspects of Java – the Collections Framework. The Java Collection Framework provides a comprehensive architecture to store and manipulate collections of objects. We will explore various collection types like ArrayList, LinkedList, HashSet, and HashMap, along with iterators and the foreach loop.

YouTube player

Java Collection

image.png

Introduction to Java Collection

In Java, a “collection” is a group of objects. The Collections Framework provides a set of classes and interfaces to work with these collections. Collections offer a way to store, retrieve, and manipulate data efficiently. They are widely used in Java for a variety of purposes.

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.

Java Project – Updategadh
updategadh.com

What is a Framework?

A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.

Methods of the Java Collection Collection Interface

Java Collection
Java Collection

This interface contains various methods which can be directly used by all the collections which implement this interface. They are:

MethodDescription
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.

Download Java :- https://www.oracle.com/in/java/technologies/downloads/

ArrayList

An ArrayList is a dynamic array that can grow or shrink as needed. It’s a part of the Java Collections Framework and allows you to store and manipulate a list of objects. Here’s how you can create an ArrayList:

javaCopy code
import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

LinkedList

A LinkedList is another type of collection that’s based on a linked data structure. It allows you to add, remove, and manipulate elements efficiently. Here’s an example:

javaCopy code
import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        for (int num : numbers) {
            System.out.println(num);
        }
    }
}
YouTube player
YouTube player

HashSet

A HashSet is an implementation of the Set interface, and it does not allow duplicate elements. It uses hashing to store elements, making it fast for retrieval. Here’s an example:

javaCopy code
import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> colors = new HashSet<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        for (String color : colors) {
            System.out.println(color);
        }
    }
}
Collage Projects – Updategadh
updategadh.com

HashMap

A HashMap is an implementation of the Map interface and stores key-value pairs. It allows you to store and retrieve values based on their keys efficiently. Here’s an example:

javaCopy code
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> studentScores = new HashMap<>();
        studentScores.put("Alice", 90);
        studentScores.put("Bob", 85);
        studentScores.put("Charlie", 78);

        for (String name : studentScores.keySet()) {
            System.out.println(name + ": " + studentScores.get(name));
        }
    }
}
Free Projects – Updategadh
updategadh.com

Iterators and foreach loop

To iterate through collections, you can use iterators or the foreach loop. Here’s an example using an ArrayList and an iterator:

javaCopy code
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        Iterator<Integer> iterator = numbers.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Alternatively, you can use a foreach loop as shown in previous examples.

Java Collection
Java Collection

Exercise Questions for Java Collection

  1. What is the Collections Framework in Java, and why is it important?
  2. What is the difference between ArrayList and LinkedList in Java?
  3. Explain the HashSet data structure and why it’s useful.
  4. How does a HashMap work, and what are its primary use cases?

Exercise Answers

  1. The Collections Framework in Java is a set of classes and interfaces that provide a standardized way to store, manipulate, and access collections of objects. It’s essential because it simplifies data manipulation and offers various data structures tailored for different scenarios.
  2. ArrayList is a dynamic array that can grow or shrink, making it suitable for random access but not for frequent insertions and deletions. LinkedList, on the other hand, is based on a linked data structure, making it efficient for insertions and deletions but less efficient for random access.
  3. HashSet is an implementation of the Set interface that does not allow duplicate elements. It uses hashing to store elements, ensuring fast retrieval and efficient uniqueness checking.
  4. A HashMap is an implementation of the Map interface, storing key-value pairs. It uses hashing to index elements based on their keys, allowing efficient retrieval and storage of key-value associations. HashMaps are commonly used for fast lookup and retrieval of values based on unique keys.

One comment

Leave a Reply

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