WEek - 05

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

Java Collections

Week 05
Instructor : Dr. Saif Ur Rehman
Lab Engineer: Muhammad Hassan Mujtaba
Course Contents- Week05
• Java Collections
• Array List Todays Contents
• Link List
• Set
• Queue
• Stack
• Map
• Lab
ArrayList
• An ArrayList is a dynamic length collection framework in Java
that also stores the elements of the same type but here we do
not need to mention the size at the time of its creation as the
case in arrays.

• In Java, we use the Array List class to implement the


functionality of resizable-arrays.

• It implements the List interface of the collections framework.


Java ArrayList Vs Array
• In Java, we need to declare the size of an array before we can use it.
Once the size of an array is declared, it's hard to change it.
• To handle this issue, we can use the ArrayList class. It allows us to
create resizable arrays.
• Unlike arrays, arraylists can automatically adjust their capacity when
we add or remove elements from them. Hence, arraylists are also
known as dynamic arrays.
Java ArrayList Vs Array
Creating an ArrayList
• Before using ArrayList, we need to import the java.util.ArrayList
package first. Here is how we can create arraylists in Java:

ArrayList<Type> arrayList= new ArrayList<>();


Here, Type indicates the type of an arraylist. For example
// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();
// create String type arraylist
ArrayList<String> arrayList = new ArrayList<>();
Creating an ArrayList
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// Add elements to ArrayList
languages.add("Java");
languages.add("Python");
languages.add("Swift");
System.out.println("ArrayList: " + languages);
}
}
Basic Operations on ArrayList
• The ArrayList class provides various methods to perform different
operations on arraylists. We will look at some commonly used arraylist
operations

• Add elements

• Access elements

• Change elements

• Remove elements
1. Add Elements to an ArrayList
import java.util.ArrayList;
• To add a single class Main {
public static void main(String[] args){
element to the
// create ArrayList
arraylist, we use the ArrayList<String> languages = new ArrayList<>();
// add() method without the index parameter
add() method of the
languages.add("Java");
ArrayList class. For languages.add("C");
languages.add("Python");
example,
System.out.println("ArrayList: " + languages);
}
}
2. Access ArrayList Elements
import java.util.ArrayList;

• To access an class Main {


public static void main(String[] args) {
element from the ArrayList<String> animals = new ArrayList<>();
// add elements in the arraylist
arraylist, we use the
animals.add("Cat");

get() method of the animals.add("Dog");


animals.add("Cow");
ArrayList class. For System.out.println("ArrayList: " + animals);
// get the element from the arraylist
example,
String str = animals.get(1);
System.out.print("Element at index 1: " + str);
}
}
3. Change ArrayList Elements
import java.util.ArrayList;
class Main {

• To change public static void main(String[] args) {

elements, We ArrayList<String> languages = new ArrayList<>();


use Set() // add elements in the array list
languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
System.out.println("ArrayList: " + languages);
// change the element of the array list
languages.set(2, "JavaScript");
System.out.println("Modified ArrayList: " + languages);
}
}
4. Remove ArrayList Elements
import java.util.ArrayList;
• To remove an class Main {
public static void main(String[] args) {
element from the ArrayList<String> animals = new ArrayList<>();
// add elements in the array list
animals.add("Dog");
arraylist, we can animals.add("Cat");
animals.add("Horse");
use the remove() System.out.println("ArrayList: " + animals);
// remove element from index 2
method of the String str = animals.remove(2);
System.out.println("Updated ArrayList: " + animals);
ArrayList class. For System.out.println("Removed Element: " + str);
}
}
example,
4. Remove All ArrayList Elements
import java.util.ArrayList;

• The Java ArrayList class Main {


public static void main(String[] args){
removeAll() method
// create an arraylist
removes all the ArrayList<String> languages = new ArrayList<>();

elements from the // add elements to arraylist


languages.add("Java");
arraylist that are languages.add("JavaScript");
languages.add("Python");
also present in the System.out.println("Programming Languages: " + languages);

specified collection. // remove all elements from arraylist


languages.removeAll(languages);
System.out.println("ArrayList after removeAll(): " + languages);
}
}
Other Methods
• Java ArrayList add() • Java ArrayList removeAll()
• inserts the element to the arraylist • removes multiple elements from the arraylist
• Java ArrayList addAll() • Java ArrayList remove()
• adds all elements of a collection to arraylist • removes the single element from the arraylist
• Java ArrayList clear() • Java ArrayList size()
• removes all the elements from arraylist • returns the length of an arraylist
• Java ArrayList clone() • Java ArrayList isEmpty()
• makes a copy of the array list • checks if the arraylist is empty
• Java ArrayList contains() • Java ArrayList subList()
• checks if the element is present in the arraylist • returns a portion of the arraylist
• Java ArrayList get() • Java ArrayList set()
• returns the element present in the specified index • replace the single element from an arraylist
• Java ArrayList indexOf()
Other Methods
• Java ArrayList toString() • Java ArrayList removeRange()
• converts the arraylist into a String • removes a portion of the arraylist
• Java ArrayList ensureCapacity() • Java ArrayList replaceAll()
• set the size of an araylist • replace all elements from the arraylist
• Java ArrayList lastIndexOf() • Java ArrayList removeIf()
• returns position of last occurrence of the element • removes element that satisfy the condition
• Java ArrayList retainAll() • Java ArrayList forEach()
• retains only the common elements • performs an action to all elements of arraylist
• Java ArrayList containsAll() • Java ArrayList iterator()
• checks if a collection is a subset of arraylist • returns an iterate to loop through the ArrayList
• Java ArrayList trimToSize()
• trims the capacity of arraylist equal to the size
Java LinkedList
• Linked List is a part of the Collection framework present in java.util package.

• This 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.
Java LinkedList
• The elements are linked using pointers and addresses.

• Each element is known as a node. Duem to the dynamicity and ease of insertions
and deletions, they are preferred over the arrays.

• It also has a few disadvantages like the nodes cannot be accessed directly instead
we need to start from the head and follow through the link to reach a node we
wish to access.
ArrayList Vs LinkedList
Java LinkedList
// Import the LinkedList class
• The LinkedList
import java.util.LinkedList;
class is almost public class Main {
public static void main(String[] args) {
identical to the
LinkedList<String> cars = new LinkedList<String>();
ArrayList: cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
How the LinkedList works
• The LinkedList stores its items in "containers." The list has a link to the
first container and each container has a link to the next container in
the list. To add an element to the list, the element is placed into a
new container and that container is linked to one of the other
containers in the list.
How the LinkedList works
• The LinkedList stores its items in "containers." The list has a link to the
first container and each container has a link to the next container in
the list. To add an element to the list, the element is placed into a
new container and that container is linked to one of the other
containers in the list.
LinkedList Methods
• add(int index, E element) • addFirst(E e)
This method Inserts the specified element at the
This method Inserts the specified element at the specified beginning of this list.
position in this list. • addLast(E e)
• add(E e) This method Appends the specified element to the end of
this list.
This method Appends the specified element to the end of this • clear()
list.
This method removes all of the elements from this list.
• addAll(int index, Collection<E> c) • clone()
This method returns a shallow copy of this LinkedList.
This method Inserts all of the elements in the specified
• contains(Object o)
collection into this list, starting at the specified position.
This method returns true if this list contains the specified
• addAll(Collection<E> c) element.

This method Appends all of the elements in the specified


collection to the end of this list, in the order that they are
returned by the specified collection’s iterator.
Set in Java
• The set interface is present in java.util package and extends the Collection
interface is an unordered collection of objects in which duplicate values cannot
be stored. It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Collection interface and adds a feature
that restricts the insertion of the duplicate elements. There are two interfaces
that extend the set implementation namely SortedSet and NavigableSet.
Queue Interface In Java
• The Queue interface is present in java.util package and extends the Collection
interface is used to hold the elements about to be processed in FIFO(First In First
Out) order. It is an ordered list of objects with its use limited to inserting
elements at the end of the list and deleting elements from the start of the list,
(i.e.), it follows the FIFO or the First-In-First-Out principle.
Queue Interface In Java
// 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);
}
}
Stack Class in Java
• Java Collection framework provides a Stack class that models and
implements a 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 said to extend Vector and treats the class as a
stack with the five mentioned functions. The class can also be referred to
as the subclass of Vector.
How to Create a Stack?
• In order to create a stack, we must import java.util.stack package and use the

Stack() constructor of this class. The below example creates an empty Stack.

• Stack<E> stack = new Stack<E>();


Java Unary Operator
// Java code for stack implementation // Searching element in the stack
import java.io.*; static void stack_search(Stack<Integer> stack, int element)
import java.util.*; {
class Test
Integer pos = (Integer) stack.search(element);
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack) if(pos == -1)
{ System.out.println("Element not found");
for(int i = 0; i < 5; i++) else
{ System.out.println("Element is found at position: " +
stack.push(i); pos);
}
}
}
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{ public static void main (String[] args)
System.out.println("Pop Operation:"); {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < 5; i++)
{
stack_push(stack);
Integer y = (Integer) stack.pop();
System.out.println(y); stack_pop(stack);
} stack_push(stack);
} stack_peek(stack);
// Displaying element on the top of the stack stack_search(stack, 2);
static void stack_peek(Stack<Integer> stack) stack_search(stack, 6);
{ }
Java HashMap
• A HashMap however, store items in "key/value" pairs, and you can access them

by an index of another type (e.g. a String).

• One object is used as a key (index) to another object (value). It can store different

types: String keys and Integer values, or the same type, like: String keys and String

values:
Add Items
• The HashMap class has many useful methods.
• For example, to add items to it, use the put() method:
Add Items
// Import the HashMap class
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}
Access an Item
• To access a value in the HashMap, use the get() method and

refer to its key:

capitalCities.get("England");
Remove an Item
• To remove an item, use the remove() method and refer to the

key:

capitalCities.remove("England");
Any Question

THANK YOU 

You might also like