KEMBAR78
Module 1 Own | PDF | Class (Computer Programming) | Queue (Abstract Data Type)
0% found this document useful (0 votes)
21 views35 pages

Module 1 Own

Uploaded by

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

Module 1 Own

Uploaded by

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

Module 1

Java Collection Framework


➢ The Java Collections Framework is a unified architecture for representing and
manipulating collections of objects.
➢ It includes interfaces, implementations, utility classes, and algorithms to make
working with collections easier and more efficient.
➢ By using the Java Collections Framework, developers can write code that is more
reusable, flexible, and maintainable

The Collection Interfaces


➢ Collection interfaces is necessary because they determine the fundamental nature of
the collection classes
➢ The Java Collections Framework is based on a set of core interfaces.
➢ These define the standard behaviors of different types of collections. Concrete
classes (like ArrayList, HashSet, etc.) implement these interfaces.
➢ In addition to the collection interfaces, collections also use the Comparator,
RandomAccess, Iterator, and ListIterator interfaces
➢ Comparator defines how two objects are compared;
➢ Iterator, ListIterator, and Spliterator enumerate the objects within a collection.
➢ By implementing RandomAccess, a list indicates that it supports efficient, random
access to its elements.
➢ To provide the greatest flexibility in their use, the collection interfaces allow some
methods to be optional.
➢ The optional methods enable you to modify the contents of a collection. Collections
that support these methods are called modifiable.
➢ Collections that do not allow their contents to be changed are called unmodifiable.
1.The ArrayList Class
The List interface is an ordered collection that allows us to add and remove elements like an
array.

Declaration:

interface List<E>

Where E is the type of elements in the list.


class ArrayList<E>
Here, E specifies the type of objects that the list will hold
The LinkedList Class

LinkedList is a part of Java’s Collections Framework and implements the List, Deque, and Queue
interfaces. It provides a doubly-linked list data structure.

Declaration:

class LinkedList<E>

Where E is the type of elements stored.

Constructors:

1. LinkedList() – creates an empty list.

2. LinkedList(Collection<? extends E> c) – creates a list initialized with elements of collection


c.
It is important to note that HashSet does not guarantee the order of its elements, because the process
of hashing doesn’t usually lend itself to the creation of sorted sets. If you need sorted storage, then
another collection, such as TreeSet, is a better choice.
import java.util.PriorityQueue;

public class Main {

public static void main(String[] args) {

// Create a PriorityQueue of integers

PriorityQueue<Integer> pq = new PriorityQueue<>();

// Add elements using offer()

pq.offer(15);

pq.offer(5);

pq.offer(20);

// Poll elements one by one (no loop)

System.out.println("First polled element: " + pq.poll()); // 5

}
SpliIterators(MQP)
➢ JDK 8 adds a new type of iterator called a spliterator that is defined by the Spliterator
interface.
➢ A spliterator cycles through a sequence of elements, and in this regard, it is similar to the
iterators just described. However, the techniques required to use it differ.
➢ Furthermore, it offers substantially more functionality than does either Iterator or ListIterator.
➢ Perhaps the most important aspect of Spliterator is its ability to provide support for parallel
iteration of portions of the sequence. Thus, Spliterator supports parallel programming
➢ One reason you might want to do so is because it offers a streamlined approach that combines
the hasNext and next operations into one method.
Spliterator is a generic interface that is declared like this

➢ Using Spliterator for basic iteration tasks is quite easy: simply call tryAdvance( ) until it
returns false.
➢ If you will be applying the same action to each element in the sequence,
forEachRemaining( ) offers a streamlined alternative.
➢ Consumer is a functional interface that applies an action to an object. It is a generic functional
interface declared in java.util.function.

Consumer specifies only one abstract method, accept( ), which is shown here:
Program Example

import java.util.*;

import java.util.function.*;

public class SpliteratorExample {

public static void main(String[] args) {

// Create a list of names

ArrayList<String> names = new ArrayList<>();

names.add("Alice");

names.add("Bob");

names.add("Charlie");

names.add("Diana");

// Obtain a Spliterator

Spliterator<String> spliterator = names.spliterator();

// Use tryAdvance() with a lambda expression

System.out.println("Using tryAdvance():");

while (spliterator.tryAdvance(name -> System.out.println("Hello, " + name)));

// If you want to reuse, you need to get a new Spliterator

spliterator = names.spliterator();

// Use forEachRemaining() to process all remaining elements

System.out.println("\nUsing forEachRemaining():");

spliterator.forEachRemaining(name -> System.out.println("Welcome, " + name));

}
Using tryAdvance():
Output:
Hello, Alice

Hello, Bob

Hello, Charlie

Hello, Diana

Using forEachRemaining():

Welcome, Alice

Welcome, Bob

Welcome, Charlie

Welcome, Diana
Define a Comparator. Mention the methods provided by the Comparator interface.
Illustrate its use with a program that demonstrates sorting elements in a TreeSet in
reverse order.(MQP)

A Comparator is a generic interface in the java.util package that defines a strategy for
comparing two objects. It is used to impose a custom ordering on a collection of objects.

Declaration:
interface Comparator<T>

Where T specifies the type of objects compared.

Methods:

1. int compare(T obj1, T obj2)

• Purpose: Core method used to compare two objects.

• Returns:

o 0 if obj1 and obj2 are considered equal.


o A positive number if obj1 > obj2.
o A negative number if obj1 < obj2.

• Usage: Must be implemented when creating a custom comparator.

2. boolean equals(Object obj)

• Purpose: Checks if the specified object is equal to the comparator.

• Returns: true if the given object is also a comparator and imposes the same ordering;
otherwise, false.

• Note: It is rarely overridden in custom comparator classes.

3. default Comparator<T> reversed() (Since JDK 8)

• Purpose: Returns a comparator with the reverse of the current comparator's order.
8. default Comparator<T> thenComparing(Comparator<? super T> other)

• Purpose: Chains comparators. If the current comparator returns 0 (equal), it uses


other to break the tie

4. static <T> Comparator<T> reverseOrder()

• Purpose: Returns a comparator that reverses the natural ordering of elements.

5. static <T> Comparator<T> naturalOrder()

• Purpose: Returns a comparator that uses natural ordering (e.g., A to Z, 1 to 100).

6. static <T> Comparator<T> nullsFirst(Comparator<? super T> comp)

• Purpose: Returns a comparator that considers null less than non-null values.

7. static <T> Comparator<T> nullsLast(Comparator<? super T> comp)

• Purpose: Returns a comparator that considers null greater than non-null values.

9. comparing(...)

• Creates a comparator based on a key extractor function.

program that demonstrates sorting elements in a TreeSet in reverse order.


// Use a custom Comparator to sort TreeSet in reverse order

import java.util.*;

class MyComp implements Comparator<String> {

public int compare(String aStr, String bStr) {


// Reverse the comparison

return bStr.compareTo(aStr);

// return aStr.compareTo(bStr); -natural Order


}

public class CompDemo {

public static void main(String args[]) {


// Create a TreeSet with custom comparator

TreeSet<String> ts = new TreeSet<String>(new MyComp());


// Add elements to the TreeSet

ts.add("C");

ts.add("A");

ts.add("B");
ts.add("E");

ts.add("F");

ts.add("D");

// Display elements - sorted in reverse order

for (String element : ts)

System.out.print(element + " ");


System.out.println();
}

}
What Are Legacy Classes in Java?

Legacy classes are the original collection classes provided by Java before the
introduction of the Java Collections Framework in JDK 1.2. These classes are part of
java.util package but were not part of the unified Collection interface hierarchy
initially.
After Java 2, most of them were retrofitted to implement collection interfaces like List,
Map, or Enumeration.

Example

import java.util.*;

public class StackExample {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<>();

stack.push(10);
stack.push(20);

stack.push(30);

System.out.println("Stack: " + stack);


System.out.println("Top element (peek): " + stack.peek());

stack.pop(); // Removes 30
System.out.println("After pop: " + stack);
}

Vector
• Stores elements dynamically like ArrayList

• Thread-safe

• Implements List

Methods
• void addElement(Object element): It inserts the element at the end of the Vector.

• int capacity(): This method returns the current capacity of the vector.

• int size(): It returns the current size of the vector.

• Object firstElement(): It is used for getting the first element of the vector.

• Object lastElement(): Returns the last element of the array.

• boolean isEmpty(): This method returns true if Vector doesn’t have any element.

import java.util.*;
public class VectorExample {

public static void main(String[] args) {

Vector<String> v = new Vector<>();

v.add("Apple");

v.add("Banana");

v.add("Mango");

System.out.println("Vector elements:");

for (String fruit : v)


System.out.println(fruit);

}
}
Hashtable
• Stores key-value pairs

• Keys and values cannot be null

• Synchronized version of HashMap

import java.util.*;

public class HashtableExample {

public static void main(String[] args) {

Hashtable<Integer, String> ht = new Hashtable<>();

ht.put(1, "One");

ht.put(2, "Two");

ht.put(3, "Three");

System.out.println("Hashtable contents:");

System.out.println(ht); // Print the hashtable directly


}

}
Properties

• Subclass of Hashtable

• Used to store configuration settings


• Keys and values are Strings

• Can be loaded from or saved to a file

import java.util.*;
public class PropertiesExample {

public static void main(String[] args) {

Properties props = new Properties();

props.setProperty("username", "admin");

props.setProperty("password", "12345");

System.out.println("Properties:");

System.out.println("Username: " + props.getProperty("username"));


System.out.println("Password: " + props.getProperty("password"));
}

Properties:

Username: admin

Password: 12345
TreeMap Sorting by Last Name (Reverse)
class Account {

String firstName;

String lastName;

Account(String firstName, String lastName) {

this.firstName = firstName;
this.lastName = lastName;

public String toString() {

return firstName + " " + lastName;

import java.util.*;
public class SimpleTreeMapSort {

public static void main(String[] args) {

// TreeMap that sorts keys (last names) in reverse order

TreeMap<String, Account> map = new TreeMap<>(Collections.reverseOrder());

// Put accounts using last name as key

map.put("Kumar", new Account("Ravi", "Kumar"));

map.put("Sharma", new Account("Anjali", "Sharma"));


map.put("Verma", new Account("Sita", "Verma"));

// Print sorted accounts

for (Account acc : map.values()) {

System.out.println(acc);

}
Collection Interface
➢ Collection interface extends the Iterable interface

➢ must be implemented by any class that defines a collection.

➢ The Collection interface is the root interface in the Java Collection Framework. It
represents a group of objects, known as elements. It is part of the java.util package.

➢ general declaration is

interface Collection < E >

E specifies the type of object that collection will hold


List Interface
➢ Extends the Collection Interface,

➢ Defines storage as sequence of elements.

➢ Following is its general declaration

interface List < E >

➢ Allows random access and insertion based on position.


➢ Allows Duplicate elements.

Methods Defined

E Remove(int index)
Collection Framework:- The Java Collections Framework is a unified
architecture for representing and manipulating collections of objects. It
includes interfaces, implementations, utility classes, and algorithms to make
working with collections easier and more efficient.
ArrayList:- The ArrayList class extends AbstractList and implements the List
interface. Implements functionality of resizable arrays
LinkedList:- The LinkedList class extends AbstractSequentialList and
implements the List, Deque, and Queue interfaces. It provides a linked-list data
structure.
HashSet:- HashSet extends AbstractSet and implements the Set interface. It
creates a collection that uses a hash table for storage.
LinkedHashSet:- The LinkedHashSet class extends HashSet and adds no
members of its own.
TreeSet:- TreeSet extends AbstractSet and implements the NavigableSet
interface. It creates a collection that uses a tree for storage. Objects are stored in
sorted, ascending order.
PriorityQueue:- PriorityQueue extends AbstractQueue and implements the
Queue interface. It creates a queue that is prioritized based on the queue’s
comparator.
Comparator:- A Comparator is a generic interface in the java.util package that
defines a strategy for comparing two objects. It is used to impose a custom
ordering on a collection of objects.

You might also like