Advanced Java

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

Advanced Java

Module 1

1
Agenda
• The collections and Framework:
 Collections Overview,
 The Collection Interfaces,
 The Collection Classes,
 Accessing a collection Via an Iterator,
 Storing User Defined Classes in Collections,
 The Random Access Interface,
 Working With Maps,
 Comparators,
 The Collection Algorithms,
 Arrays,
 The legacy Classes and Interfaces,
 Parting Thoughts on Collections.

2
Collections Overview

3
Collections Overview
• A Collection represents a single unit of objects, i.e., a
group.
• 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, Deque) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet,
4
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
• What is Collection framework
• The Collection framework represents a unified
architecture for storing and manipulating a group of
objects. It has:
1.Interfaces and its implementations, i.e., classes
2.Algorithm

5
Hierarchy of Collection framework

6
Methods of Collection Interface

7
Iterable Interface
• The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
• It contains only one abstract method. i.e.,
Iterator<T> iterator()
• It returns the iterator over the elements of type T.
8
Collection Interfaces

9
10
11
Classes that implements list
interface are,
ArrayList

LinkedList

Vector

Stack

12
ArrayList

13
14
15
16
Linked List

17
Vector

18
Stack

19
Queue

20
Priority Queue

21
Dequeue Array Dequeue

22
Set Interface

23
Hash Set

24
Linked Hash Set

25
Sorted Set Interface

26
Tree set

27
Collection Classes

28
29
• Java Collection Class
- Collection Framework contains both classes and interfaces. Although both
seem the same but there are certain
differences between Collection classes and the Collection framework. There are some
classes in Java as mentioned below:

30
31
32
33
34
35
36
// Java program to demonstrate sorting Collections.addAll(items, "Fruits", "Bat", "Mouse");
// a Collections using sort() method // Sorting according to default ordering
import java.util.ArrayList; // using sort() method
import java.util.Collections; Collections.sort(items);
import java.util.List; // Printing the elements
// Main Class for (int i = 0; i < items.size(); i++) {
// SortingCollectionExample System.out.print(items.get(i) + " ");
class GFG { }
// Main driver method System.out.println();
public static void main(String[] args) // Sorting according to reverse ordering
{ Collections.sort(items,
// Creating a list Collections.reverseOrder());
// Declaring object of string type // Printing the reverse order
List<String> items = new ArrayList<>(); for (int i = 0; i < items.size(); i++) {
// Adding elements to the list System.out.print(items.get(i) + " ");
// using add() method } }}
items.add("Shoes");
items.add("Toys");
// Adding one or more elements using addAll()

37
Collection Framework

38
Accessing a collection Via an Iterator

39
Storing User Defined Classes in Collections
• For the sake of simplicity, the foregoing
examples have stored built-in objects, such
as String or Integer, in a collection.
• Of course, collections are not limited to the
storage of built-in objects.
• The power of collections is that they can
store any type of object, including objects of
classes that you create.
• The collections can store any type of object,
including objects of classes that you create.

40
Random Access Interface
• RandomAccess interface plays a vital role in enabling random access to data structures. In this
section, we will dive into the world of random access in Java, exploring what the RandomAccess
interface is, how it works, and provide practical examples to illustrate its usage.
• The RandomAccess interface is a marker interface in Java, which means it doesn't declare any
methods of its own. Instead, it serves as a marker to indicate that a class implementing it supports
efficient random-access operations.
• By implementing this interface, a class essentially tells Java that it can provide faster access to
elements, typically using indices or keys.
• The primary reason for using the RandomAccess interface is to indicate that a class has optimized its
data structure for random access.
• This information can be beneficial for algorithms and data structures that rely on efficient random
access.
• When a class implements RandomAccess, it signals that operations like accessing elements by index
or key will be fast and efficient.

41
42
• In the above program, we create a CustomList class that implements the RandomAccess interface. We
populate it with one million integers and then access elements at random indices using the get method.
• We measure the time taken for these random-access operations. Now, let's compare the performance of
random access with and without the RandomAccess interface.
• The exact time value will depend on your machine's performance, but you should observe that the access
time with RandomAccess is faster than it would be without it.
• This demonstrates the advantage of using the RandomAccess interface when dealing with data structures
that support efficient random access.
• In Summary, The RandomAccess interface in Java is a powerful tool for optimizing random access
operations on data structures.
• By implementing this interface, classes signal that they are designed to provide efficient access to their
elements, making them ideal for use in scenarios where random access is a common requirement.
• Understanding and leveraging the RandomAccess interface can lead to significant performance
improvements in our Java applications, especially when dealing with large datasets or frequently accessed
collections.

43
MAP Interface
• In Java, Map Interface is present in java.util package represents a mapping
between a key and a value. Java Map interface is not a subtype of the
Collection interface. Therefore it behaves a bit differently from the rest of the
collection types. A map contains unique keys.
• Maps are perfect to use for key-value association mapping such as
dictionaries. The maps are used to perform lookups by keys or when
someone wants to retrieve and update elements by keys. Some common
scenarios are as follows:
 A map of error codes and their descriptions.
 A map of zip codes and cities.
 A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
 A map of classes and students. Each class (key) is associated with a list
of students (value).

44
Creating Map Objects
Since Map is an interface, objects cannot be
created of the type map. We always need a
class that extends this map in order to create
an object. And also, after the introduction of
Generics in Java 1.5, it is possible to restrict
the type of object that can be stored in the
Map.

45
Characteristics of Map Interface
1.A Map cannot contain duplicate keys and each key can map to at most one
value. Some implementations allow null key and null values like the HashMap
and LinkedHashMap, but some do not like the TreeMap.
2.The order of a map depends on the specific implementations. For example,
TreeMap and LinkedHashMap have predictable orders, while HashMap does
not.
3.There are two interfaces for implementing Map in Java. They are Map and
SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.

46
47
48
49
Map Hierarchy

50
1. HashMap
- It is a part of Java’s collection since Java 1.2. It provides the basic implementation of
the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one
must know its key. This class uses a technique called Hashing. Hashing is a technique of
converting a large String to a small String that represents the same String. A shorter
value helps in indexing and faster searches.
2. LinkedHashMap
- It is just like HashMap
with the additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search,
and deletion but it never maintained the track and order of insertion which the
LinkedHashMap provides where the elements can be accessed in their insertion order.
3. TreeMap
- It is used to implement the Map interface and NavigableMap along with the
Abstract Class. The map is sorted according to the natural ordering of its keys, or by a
Comparator provided at map creation time, depending on which constructor is used. This
proves to be an efficient way of sorting and storing the key-value pairs. The storing order
maintained by the treemap must be consistent with equals just like any other sorted map,
irrespective of the explicit comparators.
51
Performing Operations using Map Interface and HashMap Class

• Since Map is an interface, it can be used only with a class that implements this
interface.

Count the
Changing Removing Occurrence of
Adding element Iterating element
element element numbers using
Hashmap

52
1.Adding elements:

• In order to add an element to


the map, we can use the
put() method.
• However, the insertion order
is not retained in the
hashmap.
• Internally, for every element,
a separate hash is generated
and the elements are indexed
based on this hash to make it
more efficient.

53
2. Changing Element
• After adding the elements if we wish
to change the element, it can be
done by again adding the element
with the put() method.
• Since the elements in the map are
indexed using the keys, the value of
the key can be changed by simply
inserting the updated value for the
key for which we wish to change.

54
3. Removing Elements
• In order to remove an
element from the Map, we
can use the
remove() method.
• This method takes the key
value and removes the
mapping for a key from this
map if it is present in the
map.

55
4. Iterating through the Map
• There are multiple ways to
iterate through the Map.
The most famous way is to
use a for-each loop and get
the keys. The value of the
key is found by using the
getValue() method.

56
5. Count the Occurrence of numbers using Hashmap

• In this code, we are


using putIfAbsent() along
with Collections.frequency() to
count the exact occurrence of
numbers. In many programs, you
need to count the occurrence of a
particular number or letter. You use
the following approach to solve those
types of problems

57
Comparators
• A comparator interface is used to order the objects of user-
defined classes. A comparator object is capable of comparing two
objects of the same class. Following function compare obj1 with
obj2.
• Java Comparator interface is used to order the objects of a
user-defined class.
• This interface is found in java.util package and contains 2
methods compare(Object obj1,Object obj2) and equals(Object
element).
Syntax:
• It provides multiple sorting sequences, i.e., you can sort the
public int compare(Object obj1,
elements on the basis of any data member, for example, rollno,
Object obj2):
name, age or anything else.
58
Methods of Comparator

public void sort(List list, Comparator c): is used to sort the elements of List
by the given Comparator.

59
Java Comparator Example
• Let's see the example of sorting the elements of List on
the basis of age and name. In this example, we have
created 4 java classes:
1.Student.java
2.AgeComparator.java
3.NameComparator.java
4.Simple.java

60
1. Student.java

61
2. AgeComparator.java

62
3. NameComparator.java

63
4. Simple.java
• In this class, we
are printing the
values of the
object by sorting
on the basis of
name and age.

64
Collection Algorithm

65
66
import java.util.Collections; // Create a reverse order comparator
import java.util.Comparator; Comparator<Integer< r =
import java.util.Iterator; Collections.reverseOrder()
import java.util.LinkedList; // Sort list by using the comparator
import java.util.List; Collections.sort(ll, r);
public class AlgorithmsDemo { // Get iterator
public static void main(String args[]) { Iterator<Integer< li = ll.iterator();
// Create and initialize linked list System.out.print("List sorted in reverse:
List<Integer< ll = new LinkedList<<(); ");
ll.add(Integer.valueOf(-8)); while(li.hasNext()) {
ll.add(Integer.valueOf(20)); System.out.print(li.next() + " ");
ll.add(Integer.valueOf(-20)); }
ll.add(Integer.valueOf(8)); System.out.println();
}
}

67
Legacy Classes & Interfaces

68
• These include classes that tokenize strings, work with dates, compute
random numbers, bundle resources, and observe events.
1. String Tokenizer - The processing of text often consists of parsing a
formatted input string. Parsing is the division of text into a set of
discrete parts, or tokens, which in a certain sequence can convey a
semantic meaning. The StringTokenizer class provides the first step in
this parsing process, often called the lexer (lexical analyzer)
or scanner. StringTokenizer implements the Enumeration interface.
Therefore, given an input string, you can enumerate the
individual tokens contained in it using StringTokenizer.

69
2. Bitset - A BitSet class creates a special type of array that holds bit
values in the form of boolean values. This array can increase in size as
needed. This makes it similar to a vector of bits.
3. Date - The Date class encapsulates the current date and time.
4. Calendar - The abstract Calendar class provides a set of methods
that allows you to convert a time in milliseconds to a number of useful
components. Some examples of the type of information that can be
provided are year, month, day, hour, minute, and second. It is intended
that subclasses of Calendar will provide the specific functionality to
interpret time information according to their own rules. This is one
aspect of the Java class library that enables you to write programs that
can operate in international environments.

70

You might also like