0% found this document useful (0 votes)
12 views97 pages

Collections and Framework

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views97 pages

Collections and Framework

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

MODULE 1

The collections and Framework


What is collection?

• Group of objects is a collection.

• I have multiple students in a class like stud1,stud2..stud3 all together we can call it a collection
of students.

• Similarly in a organization we can have emp1,emp2..all together we can call it as collection of


employees.

• Collection is a single entity which is representing multiple objects

• In java to represent group of objects into a single entity we need certain number of classes and
interfaces.

• Collection framework will provide you those classes and interfaces.


What is collections?

• The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects.

• Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.

• Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Dequeue) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is collection framework

• Collection framework means it defines the different interfaces and classes by which
we can represent group of objects into a collection.

• I have a three students so collectively I will call as one collection .to represent group of
elements into single entity we need a special classes or interfaces .

• For example in java we have something called arraylist.

int a[]=new int[100];

Single variable which can hold multiple values.

Arraylist is equal to new arraylist when I create a object like this I can store group of
elements into a arraylist.
What is interface?

• An interface is a collection of abstract methods and constants that define a


common behavior or contract for a class that implements it.

• A method declared using the abstract keyword within an abstract class and does
not have a definition (implementation) is called an abstract method.

• A class is declared abstract using the abstract keyword. It can have zero or more
abstract and non-abstract methods.
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply {
// abstract class // if the abstract methods are not implemented, compiler will
abstract class Multiply { give an error
public int MultiplyTwo (int num1, int num2) {
// abstract methods return num1 * num2;
// sub class must implement these methods }
public abstract int MultiplyTwo (int n1, int n2); public int MultiplyThree (int num1, int num2, int num3) {
public abstract int MultiplyThree (int n1, int n2, int n3); return num1 * num2 * num3;
}
// regular method with body
public void show() { // main method
System.out.println ("Method of abstract class Multiply"); public static void main (String args[]) {
} Multiply obj = new AbstractMethodEx1();
} System.out.println ("Multiplication of 2 numbers: " +
obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " +
obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
In this example, the Drawable interface has only one method.
Its implementation is provided by Rectangle and Circle classes.
//Interface declaration: by first user In a real scenario, an interface is defined by someone else, but
interface Drawable{ its implementation is provided by different implementation
void draw(); providers. Moreover, it is used by someone else. The
} implementation part is hidden by the user who uses the
//Implementation: by second user interface.
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided
by method e.g. getDrawable()
d.draw();
}}
The relationship between classes and interfaces
What is framework

• It provides readymade architecture.

• It represents a set of classes and interfaces.

• It is optional.
Drawbacks of array

• Size is fixed(arrays are not growable in nature).

• Array can store only homogenous data.

• Data structure is not used while implementing array-it cannot support readymade

method(no predefined method- logic is required).

• To overcome this problem we have collection framework


Collection framework

• ArrayList

• List

• Hashmap

• Hashtable

• Stack
Arrays vs collections
• In array size is fixed.
• If you want add more items it will throw an exception that is index out of
range exception.
• If you want to store less element then rest of the space will be wasted.
• Collections are growable in nature .at runtime we can add or delete items.
• Collections can hold homogenous plus heterogenous data.
• Collections are implemented by underlying data structure. Ready methods
are available. When I create arraylist there is no need to write code.
Collection framework

Interfaces
• Collection(I)-which is a root interface for all other collection related classes and
interfaces which contains common methods which we can use for other collection
objects .
• For example in an organization we have objects like emp1,emp2,emp3.i will
represent as a single entity which is a collection.
• To represent this collection we need certain interfaces and classes .
• In collection we can perform adding a object, removing object and checking existence
of an object.to do this we need some collection methods. Those methods are common
across all collections. Those methods are present inside collection(I).
• Collection(I) is used to representing group of objects as a single entity and which
contains a common methods which are required for other collections .
COLLECTIONS

• Collection is a group of objects which is representing a single entity


for this we use collection(I).

• Collections which is a predefined class which is available inside


java.utils package.

• Collection class contains number of methods and those methods we


can use to perform certain operations on collection objects.
Collection interface vs collections

• Collections is a predefined class which contains some utility methods


by which we can perform certain operations on the collection objects.
It is available under java.util package.
• Collection(I) which is a base(root) interface which comes under
collection framework.
• Collection(I) which is having child interfaces.
• List(I)
• Set(I)
• Queue(I)
Methods of Collection

• add() - inserts the specified element to the collection


• size() - returns the size of the collection
• remove() - removes the specified element from the collection
• iterator() - returns an iterator to access elements of the collection
• addAll() - adds all the elements of a specified collection to the
collection
• removeAll() - removes all the elements of the specified collection
from the collection
• clear() - removes all the elements of the collection
List(I)
• List is a child interface of the collection interface .

• List is a collection in which we can store group of objects.

• Whatever the methods that are available in collection interface the same methods are available in
the list interface

When to use List?

• Suppose I want to store group of elements When I insert a new elements Insertion order should
be preserved.

• Duplicate also should allowed.

• List interface is implemented using ArrayList,Linked list,Vector(extended from stack) classes.


How to use List?

In Java, we must import java.util.List package in order to use List.

// ArrayList implementation of List


List<String> list1 = new ArrayList<>();

// LinkedList implementation of List


List<String> list2 = new LinkedList<>();
Here, we have created objects list1 and list2 of classes ArrayList and
LinkedList. These objects can use the functionalities of the List interface.
import java.util.List;
import java.util.ArrayList;

class Main {

public static void main(String[] args) {


// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();
Output
// Add elements to the list
numbers.add(1); List: [1, 2, 3]
numbers.add(2); Accessed Element: 3
numbers.add(3); Removed Element: 2
System.out.println("List: " + numbers);

// Access element from the list


int number = numbers.get(2);
System.out.println("Accessed Element: " + number);

// Remove element from the list


int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
2. Implementing the LinkedList Class // Access element from the list
int number = numbers.get(2);
import java.util.List; System.out.println("Accessed Element: " + number);
import java.util.LinkedList;
// Using the indexOf() method
class Main { int index = numbers.indexOf(2);
System.out.println("Position of 3 is " + index);
public static void main(String[] args) {
// Creating list using the LinkedList class // Remove element from the list
List<Integer> numbers = new LinkedList<>(); int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
// Add elements to the list }
numbers.add(1);
numbers.add(2);
numbers.add(3);
Output
System.out.println("List: " + numbers);
List: [1, 2, 3]
}
Accessed Element: 3
Position of 3 is 1
Removed Element: 2
toArray()

• The toArray() method in Java is used to convert a collection, such as an


ArrayList, into an array.

• This method has two forms:

1.toArray() with no arguments: This returns an array containing all the


elements of the collection. However, the type of the array is Object[]

2.toArray(T[] a): This returns an array containing all the elements of the
collection in the same type as the provided array.
import java.util.ArrayList;

public class ToArrayDemo1 {


public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();

// Add elements to the ArrayList


list.add("Banana");
Output:
list.add("Apple");
Array from ArrayList using toArray():
list.add("Orange");
Banana
list.add("Mango");
Apple
Orange
// Convert the ArrayList to an Object array
Mango
Object[] array = list.toArray();

// Print the array


System.out.println("Array from ArrayList using toArray(): ");
for (Object element : array) {
System.out.println(element);
}
}
}
import java.util.ArrayList;

public class ToArrayDemo2 {


public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();

// Add elements to the ArrayList


list.add("Banana");
list.add("Apple");
list.add("Orange"); Output
list.add("Mango"); Array from ArrayList using toArray(T[] a):
Banana
// Convert the ArrayList to a String array Apple
String[] array = new String[list.size()]; Orange
array = list.toArray(array); Mango

// Print the array


System.out.println("Array from ArrayList using toArray(T[] a): ");
for (String element : array) {
System.out.println(element);
}
}
}
Set(I)

• Set is also an interface and it’s a child interface of collection(I).

• When to use set(I)?

• Insertion order not preserved.

• Duplicates not allowed.

Set interface is implemented using HashSet,Linked Hash Set


How to use Set?

In Java, we must import java.util.Set package in order to use Set.

// Set implementation using HashSet


Set<String> animals = new HashSet<>();
Here, we have created a Set called animals. We have used the HashSet
class to implement the Set interface.
Methods of Set

• add() - adds the specified element to the set


• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified set
• retainAll() - retains all the elements in the set that are also present in another specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified collection
• hashCode() - returns a hash code value (address of the element in the set)
Set Operations

Union - to get the union of two sets x and y, we can use x.addAll(y)

Intersection - to get the intersection of two sets x and y, we can use


x.retainAll(y)

Subset - to check if x is a subset of y, we can use y.containsAll(x)


Implementing HashSet Class // Creating another set using the HashSet class
Set<Integer> set2 = new HashSet<>();
import java.util.Set;
import java.util.HashSet; // Add elements
set2.add(1);
class Main { set2.add(2);
System.out.println("Set2: " + set2);
public static void main(String[] args) {
// Creating a set using the HashSet class // Union of two sets
Set<Integer> set1 = new HashSet<>(); set2.addAll(set1);
System.out.println("Union is: " + set2);
// Add elements to the set1 }
set1.add(2); }
set1.add(3); Run Code
System.out.println("Set1: " + set1); Output

Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]
Creating a HashSet

• In order to create a hash set, we must import the java.util.HashSet package first.

• Once we import the package, here is how we can create hash sets in Java.

• // HashSet with 8 capacity and 0.75 load factor


• HashSet<Integer> numbers = new HashSet<>(8, 0.75);
• Here, the first parameter is capacity, and the second parameter is loadFactor.

• capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
• loadFactor - The load factor of this hash set is 0.6. This means, whenever our hash set is
filled by 60%, the elements are moved to a new hash table of double the size of the original
hash table.
Default capacity and load factor
• // HashSet with default capacity and load factor
• HashSet<Integer> numbers1 = new HashSet<>();
• By default,

• the capacity of the hash set will be 16


• the load factor will be 0.75
Methods of Hashset

• add() - inserts the specified element to the set

• addAll() - inserts all the elements of the specified collection to the set

• Iterator()-access the elements of hashset

• remove() - removes the specified element from the set

• removeAll() - removes all the elements from the set


Queue

• Child of the collection(I).

• The Queue interface of the Java collections framework provides the functionality
of the queue data structure. It extends the Collection interface.

When to use?
• We can use whenever objects needs to have prior to processing.

It is implemented using priority queue.


How to use Queue?
• In Java, we must import java.util.Queue package in order to use Queue.
// LinkedList implementation of Queue
Queue<String> animal1 = new LinkedList<>();

// Array implementation of Queue


Queue<String> animal2 = new ArrayDeque<>();

// Priority Queue implementation of Queue


Queue<String> animal 3 = new PriorityQueue<>();
Working of Queue Data Structure
Methods of Queue

• add() - Inserts the specified element into the queue. If the task is successful,
add() returns true, if not it throws an exception.
• offer() - Inserts the specified element into the queue. If the task is successful,
offer() returns true, if not it returns false.
• element() - Returns the head of the queue. Throws an exception if the queue is
empty.
• peek() - Returns the head of the queue. Returns null if the queue is empty.
• remove() - Returns and removes the head of the queue. Throws an exception
if the queue is empty.
• poll() - Returns and removes the head of the queue. Returns null if the queue
is empty.
Map(I)

• Map is a Independent interface. Its not a child interface of collection(I)

• Map interface is group of elements or objects in the form of key/value pair.

• Map interface is implemented by using Hashmap and Linked hashmap class.

When to use Map(I) ?


• Map interface is used whenever objects are having key and value pairs.

• Keys cannot duplicated but value can be duplicated.


Working of Map

• In Java, elements of Map are stored in key/value pairs. Keys are


unique values associated with individual Values.
Map interface methods
• put(K key, V value): Associates the specified value with the specified key in the map.

• get(Object key): Returns the value to which the specified key is mapped, or null if this map
contains no mapping for the key.

• containsKey(Object key): Returns true if this map contains a mapping for the specified key.

• remove(Object key): Removes the mapping for a key from this map if it is present.

• isEmpty(): Returns true if this map contains no key-value mappings.

• size(): Returns the number of key-value mappings in this map.

• entrySet(): Returns a Set view of the mappings contained in this map.


Methods of the Collection Interface
Methods of the Collection Interface
Methods of the Collection Interface
Collection classes

List implementations
• Arraylist
• Linked list
• Vector
ArrayList

• Arraylist is one of the class which is implemented all methods from


the list interface whatever the rules are applicable for list interface so
the same thing is applicable for array list.
• When I create an arraylist where I can create duplicate elements at the
same time insertion order is preserved.
• Arraylist is basically a class which is present under java.util package.
Declaration
ArrayList al=new ArrayList()-for heterogenous elements
Here al is a arraylist reference variable
ArrayList

• With arraylist we can store group of elements as single entity.


• to store specific type we can use the following declaration
ArrayList<string> al=new<string> ();
ArrayList Methods

• add(obj)-to insert elements orderwise.


• add(index,obj)-insertion based on position.
• size()-returns the number of objects in the ArrayList.
• remove(index)-to remove the specific element.
• get(index)-to retrieve object/value.
• set(index,obj)-to replace the elements inside the arraylist.
• contains(obj)-search object element contains in ArrayList. Returns
Boolean value
• isEmpty()-empty condition will be checked .returns Boolean value.
ArrayList Methods

• addAll()
• removeAll()
• collections.sort(al)
• Collections.shuffle(al)
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating
arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}

Output:

[Mango, Apple, Banana, Grapes]


import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
Output:
System.out.println(fruit);
System.out.println("Sorting numbers...");
Apple
List<Integer> list2=new ArrayList<Integer>();
Banana
list2.add(21);
Grapes
list2.add(11);
Mango
list2.add(51);
Sorting numbers...
list2.add(1);
1
Collections.sort(list2);
11
//Traversing list through the for-each loop
21
for(Integer number:list2)
51
System.out.println(number);
}
Converting array to arraylist

• Using Arrays.asList() Method-this method returns a fixed-size list


backed by the original array

• Using Collections.addAll() Method

• Using a Loop-You can also manually add each element of the array to
an ArrayList using a loop
import java.util.ArrayList;
import java.util.Collections;

public class Main {


public static void main(String[] args) {
// Array of integers
Integer[] array = {1, 2, 3};

// Create a new ArrayList


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

// Add all elements of the array to the ArrayList


Collections.addAll(arrayList, array);

// Print the ArrayList


System.out.println(arrayList);
}
}

[1, 2, 3]
import java.util.ArrayList;
import java.util.Collections;

public class Main {


public static void main(String[] args) {
// Array of integers
Integer[] array = {1, 2, 3};

// Create a new ArrayList


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

// Add all elements of the array to the ArrayList


Collections.addAll(arrayList, array);

// Print the ArrayList


System.out.println(arrayList);
}
}
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
// Array of doubles
double[] array = {1.1, 2.2, 3.3};

// Create a new ArrayList


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

// Add each element of the array to the ArrayList


for (double element : array) {
arrayList.add(element);
}

// Print the ArrayList


System.out.println(arrayList);
}
}
LinkedList

• The LinkedList class of the Java collections framework provides the


functionality of the linked list data structure (doubly linkedlist).
Creating a Java LinkedList

LinkedList<Type> linkedList = new LinkedList<>();


• Here, Type indicates the type of a linked list. For example,

// create Integer type linked list


LinkedList<Integer> linkedList = new LinkedList<>();

// create String type linked list


LinkedList<String> linkedList = new LinkedList<>();
Create LinkedList in Java

import java.util.LinkedList;

class Main {
public static void main(String[] args){
LinkedList: [Dog, Cat, Cow]
// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList


animals.add("Dog"); LinkedList: [Dog, Cat, Cow]
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);
}
}
Linked list Methods
• add()
• get()
• set()
• remove()
Accessing a collection Via an Iterator

• The Iterator interface of the Java collections framework allows us to

access elements of a collection. It has a subinterface ListIterator.

• All the Java collections include an iterator() method. This method

returns an instance of iterator used to iterate over elements of

collections.
Methods of Iterator

• hasNext() - returns true if there exists an element in the collection

• next() - returns the next element of the collection

• remove() - removes the last element returned by the next()

• forEachRemaining() - performs the specified action for each remaining

element of the collection


Storing User Defined Classes in Collections,

• In Java, you can store user-defined classes in collections such as lists,


sets, and maps.

• You can use collections such as ArrayList, LinkedList, HashSet,


HashMap, etc., to store instances of your user-defined classes.
comparators

• In Java, a comparator is an interface defined in the java.util package, used for


comparing objects.

• In Java, comparators are objects used to compare objects for sorting or ordering
purposes
Methods of comparator

• compare(T o1, T o2): This is the core method of the Comparator interface. It
compares two objects of type T and returns an integer value representing their
relative ordering.

• Comparing(Comparator<? super T> other): This method returns a composed


comparator that performs a subsequent comparison if the original comparator
indicates that two elements are equal. It's often used for secondary sorting criteria.
compare() method

• In Java, the compare() method is part of the Comparator interface. This method is
used to compare two objects of a particular type to determine their order.
• The compare() method returns an integer value indicating the relationship
between the two objects being compared.
int compare(T obj1, T obj2);
Where:
T is the type of objects being compared.
obj1 and obj2 are the two objects being compared
compare() method

The compare() method should return:


• a negative integer if obj1 is less than obj2.
• zero if obj1 is equal to obj2.
• a positive integer if obj1 is greater than obj2.
Random access interface

• The RandomAccess interface is a marker interface in Java that doesn't


contain any methods. Instead, it serves as a marker to indicate that a
particular class has fast, random access to its elements.

• if a List implements the RandomAccess interface, it indicates that accessing


elements by index (like get(int index)) is fast, typically in constant time. On
the other hand, if a List does not implement RandomAccess, accessing
elements by index might be slower, as in the case of linked lists.
import java.util.ArrayList;
import java.util.LinkedList; output
import java.util.List; ArrayList supports random access.
import java.util.RandomAccess; LinkedList does not support random access.
public class RandomAccessExample {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();

// Checking if the list supports random access


if (arrayList instanceof RandomAccess) {
System.out.println("ArrayList supports random access.");
} else {
System.out.println("ArrayList does not support random access.");
}

if (linkedList instanceof RandomAccess) {


System.out.println("LinkedList supports random access.");
} else {
System.out.println("LinkedList does not support random access.");
} }
}
The Collection Algorithms

• in Java, the java.util.Collection interface provides the foundation for various collection
classes, each offering different algorithms for manipulating and accessing their
elements.
• Here are some key collection algorithms available in Java:
1.Sorting Algorithms: The Collections class provides several static methods for sorting
collections. The most commonly used method is Collections.sort(List<T> list), which
sorts the elements of the specified list into ascending order.
2. Searching Algorithms: The Collections class also provides methods for searching
elements within collections, such as binarySearch(List<? extends Comparable<?
super T>> list, T key). This method searches for the specified element using the binary
search algorithm.
The Collection Algorithms
• Shuffling Algorithms: The Collections class offers shuffle(List<?> list) method,
which randomly permutes the elements in a list.
• Copying Algorithms: The Collections class provides methods like copy(List<? super
T> dest, List<? extends T> src) to copy elements from one list to another.
• Reversing Algorithms: Collections.reverse(List<?> list) reverses the order of the
elements in a list.Filling Algorithms:
• Collections.fill(List<? super T> list, T obj) method replaces all of the elements of the
specified list with the specified element.
• Frequency Counting Algorithms: Collections.frequency(Collection<?> c, Object o)
returns the number of elements in the specified collection equal to the specified object.
import java.util.*;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 9, 1, 7));

// Sorting in ascending order


Collections.sort(numbers);
System.out.println("Sorted numbers in ascending order: " + numbers);

// Sorting in descending order


Collections.sort(numbers, Collections.reverseOrder());
System.out.println("Sorted numbers in descending order: " + numbers);
}
}

Output
Sorted numbers in ascending order: [1, 2, 5, 7, 9]
Sorted numbers in descending order: [9, 7, 5, 2, 1]
import java.util.*;

public class Main {


public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 7};

// Sorting in ascending order


Arrays.sort(numbers);
System.out.println("Sorted numbers in ascending order: " + Arrays.toString(numbers));

// Sorting in descending order


Arrays.sort(numbers);
System.out.println("Sorted numbers in descending order: " + Arrays.toString(numbers));
}
}

Output
Sorted numbers in ascending order: [1, 2, 5, 7, 9]
Sorted numbers in descending order: [1, 2, 5, 7, 9]
Custom sort
import java.util.*;

class CustomComparator implements Comparator<String> {


@Override
public int compare(String s1, String s2) {
// Custom sorting logic here
return s1.length() - s2.length(); // Sort by length
}
}

public class Main {


public static void main(String[] args) {
List<String> strings = new ArrayList<>(Arrays.asList("apple", "banana", "kiwi", "orange"));

// Sorting using custom comparator


Collections.sort(strings, new CustomComparator());

System.out.println("Sorted strings by length: " + strings);


}
}

Sorted strings by length: [kiwi, apple, banana, orange]


Shuffling algorithms

• Collections.shuffle() method to shuffle elements in a list:java


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ShufflingAlgorithms {


Original list:
public static void main(String[] args) { [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List<Integer> list = new ArrayList<>(); Shuffled list:
for (int i = 1; i <= 10; i++) { [9, 2, 6, 3, 7, 1, 10, 4, 5, 8]
list.add(i);
}

System.out.println("Original list:");
System.out.println(list);

// Shuffle the list


Collections.shuffle(list);

System.out.println("Shuffled list:");
System.out.println(list);
}
}
Searching algorithms

Linear Search: It sequentially checks each element of the list until a match is found
or the whole list has been searched.
Binary Search: It works on sorted arrays by repeatedly dividing the search interval
in half until the value is found or the interval is empty.
Depth-First Search (DFS): It traverses a graph or tree by exploring as far as
possible along each branch before backtracking.
Breadth-First Search (BFS): It explores all neighbor nodes at the present depth
prior to moving on to the nodes at the next depth level.
A Search Algorithm*: It is a best-first search algorithm that uses a heuristic to
efficiently search for a path with the lowest cost.
collections.fill()

• Collections.fill(), which is used to replace all elements of a specified


list with a provided value.
• Syntax:The fill() method in Collections has the following signature:
public static <T> void fill(List<? super T> list, T obj)
Parameters
list: This is the list whose elements are to be replaced.
obj: This is the object that will replace all elements in the list.
import java.util.*;

public class Main {


public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana"); Output
fruits.add("Cherry"); Original list: [Apple, Banana, Cherry]
List after filling: [Orange, Orange, Orange]
System.out.println("Original list: " + fruits);

// Using Collections.fill() to replace all elements with "Orange"


Collections.fill(fruits, "Orange");

System.out.println("List after filling: " + fruits);


}
}
asList()
• asList is a method provided by the Arrays class and List interface that allows you to convert an array into a
fixed-size list.

import java.util.*;
public class Main {
public static void main(String[] args) {
// Create an array of strings
String[] array = {"apple", "banana", "cherry"};

// Convert array to list using Arrays.asList()


List<String> list = Arrays.asList(array);

// Print the list


System.out.println("List: " + list);
}
}
Frequency Counting Algorithms:
• You can use the Collections.frequency() method from the java.util.Collections class to count occurrences
of an element in a List.

import java.util.*;
public class FrequencyExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");

// Count frequency of "apple"


int frequency = Collections.frequency(list, "apple");
System.out.println("Frequency of 'apple': " + frequency); // Output: Frequency of 'apple': 3
}
}
Routine Data Manipulation

• In Java, the collections framework provides different methods that can


be used to manipulate data.

• reverse() - reverses the order of elements


• fill() - replace every element in a collection with the specified value
• copy() - creates a copy of elements from the specified source to
destination
• swap() - swaps the position of two elements in a collection
• addAll() - adds all the elements of a collection to other collection
Finding Extreme Values

• The min() and max() methods of the Java collections framework are
used to find the minimum and the maximum elements, respectively.
import java.util.Collections;
import java.util.ArrayList;

class Main {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Output
// Using min()
int min = Collections.min(numbers); Minimum Element: 1
System.out.println("Minimum Element: " + min); Maximum Element: 3

// Using max()
int max = Collections.max(numbers);
System.out.println("Maximum Element: " + max);
}
}
Legacy classes and interfaces
• In Java, "legacy" classes and interfaces typically refer to those that
were part of earlier versions of the Java language and its standard
libraries.
• These classes and interfaces may still be in use but are considered
outdated or superseded by newer alternatives introduced in later
versions of Java.
Enumeration interface

1.Enumeration interface defines method to enumerate(obtain one at a time)


through collection of objects.
2.This interface is superseded(replaced) by Iterator interface.
3.However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.
4.It specifies the following two methods
boolean hasMoreElements() //It returns true while there are still more elements to
extract,and returns false when all the elements have been enumerated.

Object nextElement() //It returns the next object in the enumeration i.e. each call to
nextElement() method obtains the next object in the enumeration. It throws
NoSuchElementException when the enumeration is complete.
vector
• Vector is a special type of ArrayList that defines a dynamic array.
ArrayList is not synchronized while vector is synchronized.
• The vector class has several legacy methods that are not present in the
collection framework.
• Vector class has following four constructors
vector
• Vector() //This creates a default vector, which has an initial size of 10.

• Vector(int size) //This creates a vector whose initial capacity is specified by size.

• Vector(int size, int incr) //This creates a vector whose initial capacity is specified
by size and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time when a vector is resized for addition of
objects.

• Vector(Collection c) //This creates a vector that contains the elements of


collection c.
Method Description

void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector


import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector<Integer> ve = new Vector<Integer>();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);

Enumeration<Integer> en = ve.elements(); output


10
while(en.hasMoreElements()) 20
{ 30
System.out.println(en.nextElement()); 40
} 50
} 60

}
Hashtable class

1.Like HashMap, Hashtable also stores key/value pair. However neither

keys nor values can be null.

2.There is one more difference between HashMap and Hashtable that is

Hashtable is synchronized while HashMap is not.

3.Hashtable has following four constructor


Hashtable class

Hashtable() //This is the default constructor. The default size is 11.

Hashtable(int size) //This creates a hash table that has an initial size specified by size.

Hashtable(int size, float fillratio) //This creates a hash table that has an initial size specified by size
and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how
full the hash table can be before it is resized upward. Specifically, when the number of elements is
greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded.

If you do not specify a fill ratio, then 0.75 is used.

Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is initialized with
the elements in m. The capacity of the hash table is set to twice the number of elements in m.

The default load factor of 0.75 is used.


stack class
• Stack class extends Vector.
• It follows last-in, first-out principle for the stack elements.
• It defines only one default constructor
Stack() //This creates an empty stack
If you want to put an object on the top of the stack, call push() method.
If you want to remove and return the top element, call pop() method. An
EmptyStackException is thrown if you call pop() method when the
invoking stack is empty.
import java.util.*;
class StackDemo {
public static void main(String args[]) {
Stack st = new Stack();
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();
output
while(e1.hasMoreElements())
11 22 33 44 55
System.out.print(e1.nextElement()+" ");
After popping out two elements
11 22 33
st.pop();
st.pop();

System.out.println("\nAfter popping out two elements");

Enumeration e2 = st.elements();

while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
}}

You might also like