0% found this document useful (0 votes)
6 views47 pages

Unit 3&unit 4 Notes Oosj

The document provides an overview of Java programming concepts, including string handling with text blocks, the use of records for data transfer objects (DTOs), and the implementation of sealed classes. It also explains the Java Collections Framework, detailing its interfaces and classes such as List, ArrayList, LinkedList, and Vector, along with their functionalities. Additionally, it highlights the advantages of using the Collection Framework and the need for a unified architecture for managing groups of objects in Java.

Uploaded by

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

Unit 3&unit 4 Notes Oosj

The document provides an overview of Java programming concepts, including string handling with text blocks, the use of records for data transfer objects (DTOs), and the implementation of sealed classes. It also explains the Java Collections Framework, detailing its interfaces and classes such as List, ArrayList, LinkedList, and Vector, along with their functionalities. Additionally, it highlights the advantages of using the Collection Framework and the need for a unified architecture for managing groups of objects in Java.

Uploaded by

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

Text Blocks

// Using a literal string

String text1 = "Geeks For Geeks";

// Using a text block

String text2 = """ Geeks For Geeks""";

// Both text1 and text2 are strings of equal value

text1.equals(text2) // true

// Both text1 and text2 intern to the same string

text1 == text2 // true

// ORIGINAL

String message = "A-143, 9th Floor, Sovereign Corporate Tower,\n" +

"Sector-136, Noida,\n" + "Uttar Pradesh - 201305";

// BETTER: Using text blocks

// gets rid of lots of the clutter

String message = """

A-143, 9th Floor, Sovereign Corporate Tower,

Sector-136, Noida, Uttar Pradesh - 201305""";

RECORDS:

// A simple Employee class to be used as a DTO

public record Employee(int id, String firstName,


String lastName) {

Example 1

// Creating Employee object and showcasing its use cases

// Main class
class GFG {

// Main driver method

public static void main(String args[]) {

// Creating object with default constructor

Employee e1 = new Employee(1001, "Derok", "Dranf");

// Auto generated getter methods

System.out.println(e1.id() + " " + e1.firstName()

+ " " + e1.lastName());

// Auto-generated toString() method

System.out.println(e1.toString());

Output:

1001 Derok Dranf

Employee[id=1001, firstName=Derok, lastName=Dranf]

EXAMPLE 2:

// Java Program to Illustrate Record's functionalities

// Main class

class GFG {

// Main driver method

public static void main(String args[]) {

// Creating object with default constructor

Employee e1 = new Employee(1001, "Derok", "Dranf");

// auto generated getter methods


System.out.println(e1.id() + " " + e1.firstName()

+ " " + e1.lastName());

// Auto-generated toString() method

System.out.println(e1.toString());

// Creating object with parameterized constructor

Employee e2 = new Employee(1002, "Seren");

// Using instance methods

e2.getFullName();

// Using static methods

System.out.println("Employee " + e2.id()

+ " Token = "

+ e2.generateEmployeeToken());

// Using the equals() method

System.out.print("Is e1 equal to e2: "

+ e1.equals(e2));

Output:

1001 Derok Dranf

Employee[id=1001, firstName=Derok, lastName=Dranf]

Seren

Employee 1002 Token = 1

Is e1 equal to e2: false

Sealed Class in Java

Example
sealed class Human permits Manish, Vartika, Anjali

public void printName()

System.out.println("Default");

non-sealed class Manish extends Human

public void printName()

System.out.println("Manish Sharma");

sealed class Vartika extends Human

public void printName()

System.out.println("Vartika Dadheech");

final class Anjali extends Human

public void printName()

{
System.out.println("Anjali Sharma");

Explanation of the above Example:

Human is the parent class of Manish, Vartika, and Anjali. It is a sealed class so; other classes
cannot inherit it.

Manish, Vartika, and Anjali are child classes of the Human class, and it is necessary to make
them either sealed, non-sealed, or final. Child classes of a sealed class must be sealed, non-
sealed, or final.

If any class other than Manish, Vartika, and Anjali tries to inherit from the Human class, it
will cause a compiler error.

EXAMPLE:

import java.lang.*;

sealed class Human permits Manish, Vartika, Anjali

public void printName()

System.out.println("Default");

non-sealed class Manish extends Human

public void printName()

System.out.println("Manish Sharma");

}
}

sealed class Vartika extends Human

public void printName()

System.out.println("Vartika Dadheech");

final class Anjali extends Human

public void printName()

System.out.println("Anjali Sharma");

public class Main

public static void main(String[] args)

Human h1 = new Anjali();

Human h2 = new Vartika();

Human h3 = new Manish();


h1.printName();

h2.printName();

h3.printName();

Collections in Java

Any group of individual objects that are represented as a single unit is known as a Java
Collection of Objects. In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it.

In Java, the Collection interface (java.util.Collection) and Map interface (java.util.Map) are the
two main “root” interfaces of Java collection classes.

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, TreeSet).
What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

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:

Interfaces and its implementations, i.e., classes

Algorithm

Advantages of the Java Collection Framework

Since the lack of a collection framework gave rise to the above set of disadvantages, the
following are the advantages of the collection framework.

1. Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map,
all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have
some common set of methods.

2. Reduces programming effort: A programmer doesn’t have to worry about the design of
the Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented programming (i.e.) abstraction has been successfully
implemented.

3. Increases program speed and quality: Increases performance by providing high-


performance implementations of useful data structures and algorithms because in this
case, the programmer need not think of the best implementation of a specific data
structure. He can simply use the best implementation to drastically boost the performance
of his algorithm/program.
Hierarchy of the Collection Framework in Java

The utility package, (java.util) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable
interface which provides the iterator to iterate through all the collections. This interface is
extended by the main collection interface which acts as a root for the collection framework. All
the collections extend this collection interface thereby extending the properties of the iterator and
the methods of this interface. The following figure illustrates the hierarchy of the collection
framework.

Before understanding the different components in the above framework, let’s first understand a
class and an interface.

 Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.

 Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, nobody).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
What is a Framework in Java?

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.

Need for a Separate Collection Framework in Java

Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these
collections had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no
correlation among them. And also, it is very difficult for the users to remember all the different
methods, syntax, and constructors present in every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.

Example:

// Java program to demonstrate


// why collection framework was needed
import java.io.*;
import java.util.*;

class CollectionDemo {

public static void main(String[] args)


{
// Creating instances of the array,
// vector and hashtable
int arr[] = new int[] { 1, 2, 3, 4 };
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h = new Hashtable();

// Adding the elements into the


// vector
v.addElement(1);
v.addElement(2);

// Adding the element into the


// hashtable
h.put(1, "geeks");
h.put(2, "4geeks");

// Array instance creation requires [],


// while Vector and hastable require ()
// Vector element insertion requires addElement(),
// but hashtable element insertion requires put()

// Accessing the first element of the


// array, vector and hashtable
System.out.println(arr[0]);
System.out.println(v.elementAt(0));
System.out.println(h.get(1));

// Array elements are accessed using [],


// vector elements using elementAt()
// and hashtable elements using get()
}
}
Output
1
1
geeks

Interfaces that extend the Java Collections Interface

The collection framework contains multiple interfaces where every interface is used to store a
specific type of data. The following are the interfaces present in the framework.

1. Iterable Interface

This is the root interface for the entire collection framework. The collection interface extends the
iterable interface. Therefore, inherently, all the interfaces and classes implement this interface.
The main functionality of this interface is to provide an iterator for the collections. Therefore,
this interface contains only one abstract method which is the iterator. It returns the

Iterator iterator();

2. Collection Interface

This interface extends the iterable interface and is implemented by all the classes in the
collection framework. This interface contains all the basic methods which every collection has
like adding the data into the collection, removing the data, clearing the data, etc. All these
methods are implemented in this interface because these methods are implemented by all the
classes irrespective of their style of implementation. And also, having these methods in this
interface ensures that the names of the methods are universal for all the collections. Therefore, in
short, we can say that this interface builds a foundation on which the collection classes are
implemented.
3. List Interface

This is a child interface of the collection interface. This interface is dedicated to the data of the
list type in which we can store all the ordered collections of the objects. This also allows
duplicate data to be present in it. This list interface is implemented by various classes like
ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list
object with any of these classes.

For example:

List <T> al = new ArrayList<> ();


List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object

The classes which implement the List interface are as follows:

i). ArrayList

ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is needed. The size
of an ArrayList is increased automatically if the collection grows or shrinks if the objects are
removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can
not be used for primitive types, like int, char, etc. We will need a wrapper class for such cases.

Let’s understand the ArrayList with the following example:

// Java program to demonstrate the

// working of ArrayList

import java.io.*;

import java.util.*;

class GFG {

// Main Method

public static void main(String[] args)

{
// Declaring the ArrayList with

// initial size n

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

// Appending new elements at

// the end of the list

for (int i = 1; i <= 5; i++)

al.add(i);

// Printing elements

System.out.println(al);

// Remove element at index 3

al.remove(3);

// Displaying the ArrayList

// after deletion

System.out.println(al);

// Printing elements one by one

for (int i = 0; i < al.size(); i++)

System.out.print(al.get(i) + " ");

}
}

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235

ii). LinkedList

The LinkedList 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. The elements are linked using pointers and
addresses. Each element is known as a node.

Let’s understand the LinkedList with the following example:

// Java program to demonstrate the

// working of LinkedList

import java.io.*;

import java.util.*;

class GFG {

// Main Method

public static void main(String[] args)

// Declaring the LinkedList

LinkedList<Integer> ll = new
LinkedList<Integer>();
// Appending new elements at

// the end of the list

for (int i = 1; i <= 5; i++)

ll.add(i);

// Printing elements

System.out.println(ll);

// Remove element at index 3

ll.remove(3);

// Displaying the List

// after deletion

System.out.println(ll);

// Printing elements one by one

for (int i = 0; i < ll.size(); i++)

System.out.print(ll.get(i) + " ");

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
iii). Vector

A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. This is identical
to ArrayList in terms of implementation. However, the primary difference between a vector and
an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.

Let’s understand the Vector with an example:

// Java program to demonstrate the

// working of Vector

import java.io.*;

import java.util.*;

class GFG {

// Main Method

public static void main(String[] args)

// Declaring the Vector

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

// Appending new elements at

// the end of the list

for (int i = 1; i <= 5; i++)

v.add(i);
// Printing elements

System.out.println(v);

// Remove element at index 3

v.remove(3);

// Displaying the Vector

// after deletion

System.out.println(v);

// Printing elements one by one

for (int i = 0; i < v.size(); i++)

System.out.print(v.get(i) + " ");

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235

iv). Stack

Stack class models and implements the 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 empty, search, and peek. The class can also be referred to as the subclass of
Vector.
Let’s understand the stack with an example:

// Java program to demonstrate the

// working of a stack

import java.util.*;

public class GFG {

// Main Method

public static void main(String args[])

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

stack.push("Geeks");

stack.push("For");

stack.push("Geeks");

stack.push("Geeks");

// Iterator for the stack

Iterator<String> itr = stack.iterator();

// Printing the stack

while (itr.hasNext()) {

System.out.print(itr.next() + " ");

System.out.println();
stack.pop();

// Iterator for the stack

itr = stack.iterator();

// Printing the stack

while (itr.hasNext()) {

System.out.print(itr.next() + " ");

Output

Geeks For Geeks Geeks


Geeks For Geeks

Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead
in an environment where thread safety is not needed. An alternate to Stack is to use
ArrayDequeue which is not thread-safe and has faster array implementation.

4. Queue Interface

As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a
real-world queue line. This interface is dedicated to storing all the elements where the order of
the elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first
come first serve basis. Therefore, the person whose request arrives first into the queue gets the
ticket. There are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses
implement the queue, we can instantiate a queue object with any of these classes.

For example:

Queue <T> pq = new PriorityQueue<> ();


Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.

The most frequently used implementation of the queue interface is the PriorityQueue.

Priority Queue

A PriorityQueue is used when the objects are supposed to be processed based on priority. It is
known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the
queue are needed to be processed according to the priority and this class is used in these cases.
The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered
according to the natural ordering, or by a Comparator provided at queue construction time,
depending on which constructor is used.

Let’s understand the priority queue with an example:

// Java program to demonstrate the working of

// priority queue in Java

import java.util.*;

class GfG {

// Main Method

public static void main(String args[])

// Creating empty priority queue

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

// Adding items to the pQueue using add()


pQueue.add(10);

pQueue.add(20);

pQueue.add(15);

// Printing the top element of PriorityQueue

System.out.println(pQueue.peek());

// Printing the top element and removing it

// from the PriorityQueue container

System.out.println(pQueue.poll());

// Printing the top element again

System.out.println(pQueue.peek());

Output

10
10
15

5. Deque Interface

This is a very slight variation of the queue data structure. Deque, also known as a double-ended
queue, is a data structure where we can add and remove elements from both ends of the queue.
This interface extends the queue interface. The class which implements this interface is
ArrayDeque. Since ArrayDeque class implements the Deque interface, we can instantiate a
deque object with this class.

For example:

Deque<T> ad = new ArrayDeque<> ();


Where T is the type of the object.
The class which implements the deque interface is ArrayDeque.

ArrayDeque

ArrayDeque class which is implemented in the collection framework provides us with a way to
apply resizable array. This is a special kind of array that grows and allows users to add or
remove an element from both sides of the queue. Array deques have no capacity restrictions and
they grow as necessary to support usage. Let’s understand ArrayDeque with an example:
// Java program to demonstrate the ArrayDeque class in Java

import java.util.*;

public class ArrayDequeDemo {

public static void main(String[] args)

{ // Initializing an deque

ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10);

// add() method to insert

de_que.add(10);

de_que.add(20);

de_que.add(30);

de_que.add(40);

de_que.add(50);

System.out.println(de_que);

// clear() method

de_que.clear();

// addFirst() method to insert the elements at the head

de_que.addFirst(564);

de_que.addFirst(291);

// addLast() method to insert the elements at the tail

de_que.addLast(24);

de_que.addLast(14);

System.out.println(de_que);

}}
Output

[10, 20, 30, 40, 50]


[291, 564, 24, 14]

6. Set Interface

A set is an unordered collection of objects in which duplicate values cannot be stored. This
collection is used when we wish to avoid the duplication of the objects and wish to store only the
unique objects. This set interface is implemented by various classes like HashSet, TreeSet,
LinkedHashSet, etc. Since all the subclasses implement the set, we can instantiate a set object
with any of these classes. For example:

Set<T> hs = new HashSet<> ();


Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
Where T is the type of the object.
The following are the classes that implement the Set interface:

i). HashSet

The HashSet class is an inherent implementation of the hash table data structure. The objects that
we insert into the HashSet do not guarantee to be inserted in the same order. The objects are
inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s
understand HashSet with an example:

// Java program to demonstrate the working of a HashSet

import java.util.*;

public class HashSetDemo {

public static void main(String args[])

// Creating HashSet and adding elements

HashSet<String> hs = new HashSet<String>();

hs.add("Geeks");

hs.add("For");

hs.add("Geeks");
hs.add("Is");

hs.add("Very helpful");

// Traversing elements

Iterator<String> itr = hs.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

} }}

Output

Very helpful
Geeks
For
Is

ii). LinkedHashSet

A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked
list to store the data and retains the ordering of the elements. Let’s understand the LinkedHashSet
with an example:

// Java program to demonstrate the

// working of a LinkedHashSet

import java.util.*;

public class LinkedHashSetDemo {

// Main Method

public static void main(String args[])

// Creating LinkedHashSet and


// adding elements

LinkedHashSet<String> lhs

= new LinkedHashSet<String>();

lhs.add("Geeks");

lhs.add("For");

lhs.add("Geeks");

lhs.add("Is");

lhs.add("Very helpful");

// Traversing elements

Iterator<String> itr = lhs.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

Output

Geeks
For
Is
Very helpful

7. Sorted Set Interface

This interface is very similar to the set interface. The only difference is that this interface has
extra methods that maintain the ordering of the elements. The sorted set interface extends the set
interface and is used to handle the data which needs to be sorted. The class which implements
this interface is TreeSet. Since this class implements the SortedSet, we can instantiate a
SortedSet object with this class.

For example:

SortedSet<T> ts = new TreeSet<> ();


Where T is the type of the object.

The class which implements the sorted set interface is TreeSet.

TreeSet

The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set
using their natural ordering whether or not an explicit comparator is provided. This must be
consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a
Comparator provided at a set creation time, depending on which constructor is used.

Let’s understand TreeSet with an example:

// Java program to demonstrate the working of a TreeSet

import java.util.*;

public class TreeSetDemo {

public static void main(String args[])

// Creating TreeSet and adding elements

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

ts.add("Geeks");

ts.add("For");

ts.add("Geeks");

ts.add("Is");

ts.add("Very helpful");

// Traversing elements
Iterator<String> itr = ts.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

} }}

Output

For
Geeks
Is
Very helpful

8. Map Interface

A map is a data structure that supports the key-value pair for mapping the data. This interface
doesn’t support duplicate keys because the same key cannot have multiple mappings; however, it
allows duplicate values in different keys. A map is useful if there is data and we wish to perform
operations on the basis of the key. This map interface is implemented by various classes like
HashMap, TreeMap, etc. Since all the subclasses implement the map, we can instantiate a map
object with any of these classes.

For example:

Map<T> hm = new HashMap<> ();


Map<T> tm = new TreeMap<> ();

Where T is the type of the object.


The frequently used implementation of a Map interface is a HashMap.

HashMap

HashMap provides the basic implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a
technique called Hashing. Hashing is a technique of converting a large String to a small String
that represents the same String so that the indexing and search operations are faster. HashSet also
uses HashMap internally. Let’s understand the HashMap with an example:

// Java program to demonstrate the working of a HashMap

import java.util.*;

public class HashMapDemo {


public static void main(String args[])

// Creating HashMap and adding elements

HashMap<Integer, String> hm = new HashMap<Integer, String>();

hm.put(1, "Geeks");

hm.put(2, "For");

hm.put(3, "Geeks");

// Finding the value for a key

System.out.println("Value for 1 is " + hm.get(1));

// Traversing through the HashMap

for (Map.Entry<Integer, String> e : hm.entrySet())

System.out.println(e.getKey() + " " + e.getValue());

}}

Output

Value for 1 is Geeks


1 Geeks
2 For
3 Geeks

LinkedHashMap in Java

The LinkedHashMap Class is just like HashMap with an 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.

Important Features of a LinkedHashMap are listed as follows:

 A LinkedHashMap contains values based on the key. It implements the Map interface
and extends the HashMap class.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It is non-synchronized.
 It is the same as HashMap with an additional feature that it maintains insertion order. For
example, when we run the code with a HashMap, we get a different order of elements.

Declaration:

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

Here, K is the key Object type and V is the value Object type

 K – The type of the keys in the map.


 V – The type of values mapped in the map.

It implements Map<K, V> interface, and extends HashMap<K, V> class. Though the Hierarchy
of LinkedHashMap is as depicted in below media as follows:

How LinkedHashMap Work Internally?

A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.
Therefore, the class is declared as:

public class LinkedHashMap


extends HashMap
implements Map

In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap
is very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is
represented as:
 Hash: All the input keys are converted into a hash which is a shorter form of the key so
that the search and insertion are faster.
 Key: Since this class extends HashMap, the data is stored in the form of a key-value pair.
Therefore, this parameter is the key to the data.
 Value: For every key, there is a value associated with it. This parameter stores the value
of the keys. Due to generics, this value can be of any form.
 Next: Since the LinkedHashMap stores the insertion order, this contains the address to
the next node of the LinkedHashMap.
 Previous: This parameter contains the address to the previous node of the
LinkedHashMap.

// Java Program to Demonstrate Working of LinkedHashMap

// Importing required classes


import java.util.*;

// LinkedHashMapExample
public class GFG {

// Main driver method


public static void main(String a[])
{

// Creating an empty LinkedHashMap


LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();

// Adding entries in Map


// using put() method
lhm.put("one", "practice.geeksforgeeks.org");
lhm.put("two", "code.geeksforgeeks.org");
lhm.put("four", "www.geeksforgeeks.org");

// Printing all entries inside Map


System.out.println(lhm);

// Note: It prints the elements in same order


// as they were inserted

// Getting and printing value for a specific key


System.out.println("Getting value for key 'one': "
+ lhm.get("one"));

// Getting size of Map using size() method


System.out.println("Size of the map: "
+ lhm.size());

// Checking whether Map is empty or not


System.out.println("Is map empty? "
+ lhm.isEmpty());

// Using containsKey() method to check for a key


System.out.println("Contains key 'two'? "
+ lhm.containsKey("two"));

// Using containsKey() method to check for a value


System.out.println(
"Contains value 'practice.geeks"
+ "forgeeks.org'? "
+ lhm.containsValue("practice"
+
".geeksforgeeks.org"));

// Removing entry using remove() method


System.out.println("delete element 'one': "
+ lhm.remove("one"));

// Printing mappings to the console


System.out.println("Mappings of LinkedHashMap : "
+ lhm);
}
}

Output
{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=www.geeksforgeeks.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
Mappings of LinkedHashMap : {two=code.geeksforgeeks.org, four=www.geeksforgeeks.org}

Various operations on the LinkedHashMap class

Let’s see how to perform a few frequently used operations on the LinkedHashMap class
instance.
Operation 1: Adding Elements

In order to add an element to the LinkedHashMap, we can use the put() method. This is different
from HashMap because in HashMap, the insertion order is not retained but it is retained in the
LinkedHashMap.

Example

// Java Program to Demonstrate Adding

// Elements to a LinkedHashMap

// Importing required classes

import java.util.*;

// Main class

// AddElementsToLinkedHashMap

class GFG {

// Main driver method

public static void main(String args[])

// Initialization of a LinkedHashMap

// using Generics

LinkedHashMap<Integer, String> hm1

= new LinkedHashMap<Integer, String>();

// Add mappings to Map

// using put() method

hm1.put(3, "Geeks");

hm1.put(2, "For");

hm1.put(1, "Geeks");
// Printing mappings to the console

System.out.println("Mappings of LinkedHashMap : "

+ hm1);

Output

Mappings of LinkedHashMap : {3=Geeks, 2=For, 1=Geeks}

Operation 2: Changing/Updating Elements

After adding elements if we wish to change the element, it can be done by again adding the
element using the put() method. Since the elements in the LinkedHashMap are indexed using the
keys, the value of the key can be changed by simply re-inserting the updated value for the key
for which we wish to change.

Example

// Java Program to Demonstrate Updation of Elements

// of LinkedHashMap

import java.util.*;

// Main class

// UpdatingLinkedHashMap

class GFG {

// Main driver method

public static void main(String args[])

// Initialization of a LinkedHashMap

// using Generics

LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();

// Inserting mappings into Map

// using put() method

hm.put(3, "Geeks");

hm.put(2, "Geeks");

hm.put(1, "Geeks");

// Printing mappings to the console

System.out.println("Initial map : " + hm);

// Updating the value with key 2

hm.put(2, "For");

// Printing the updated Map

System.out.println("Updated Map : " + hm);

Output

Initial map : {3=Geeks, 2=Geeks, 1=Geeks}


Updated Map : {3=Geeks, 2=For, 1=Geeks}

Operation 3: Removing Element

In order to remove an element from the LinkedHashMap, we can use the remove() method. This
method takes the value of key as input, searches for existence of such key and then removes the
mapping for the key from this LinkedHashMap if it is present in the map. Apart from that, we
can also remove the first entered element from the map if the maximum size is defined.

Example

// Java program to Demonstrate Removal of Elements

// from LinkedHashMap

// Importing utility classes


import java.util.*;

// Main class

// RemovingMappingsFromLinkedHashMap

class GFG {

// Main driver method

public static void main(String args[])

// Initialization of a LinkedHashMap

// using Generics

LinkedHashMap<Integer, String> hm

= new LinkedHashMap<Integer, String>();

// Inserting the Elements

// using put() method

hm.put(3, "Geeks");

hm.put(2, "Geeks");

hm.put(1, "Geeks");

hm.put(4, "For");

// Printing the mappings to the console

System.out.println("Initial Map : " + hm);

// Removing the mapping with Key 4

hm.remove(4);

// Printing the updated map

System.out.println("Updated Map : " + hm);

}
Output

Initial Map : {3=Geeks, 2=Geeks, 1=Geeks, 4=For}


Updated Map : {3=Geeks, 2=Geeks, 1=Geeks}

Operation 4: Iterating through the LinkedHashMap

There are multiple ways to iterate through the LinkedHashMap. The most famous way is to use a
for-each loop over the set view of the map (fetched using map.entrySet() instance method). Then
for each entry (set element) the values of key and value can be fetched usingthe getKey() and the
getValue() method.

Example

// Java program to demonstrate

// Iterating over LinkedHashMap

// Importing required classes

import java.util.*;

// Main class

// IteratingOverLinkedHashMap

class GFG {

// Main driver method

public static void main(String args[])

// Initialization of a LinkedHashMap

// using Generics

LinkedHashMap<Integer, String> hm

= new LinkedHashMap<Integer, String>();

// Inserting elements into Map

// using put() method

hm.put(3, "Geeks");
hm.put(2, "For");

hm.put(1, "Geeks");

// For-each loop for traversal over Map

for (Map.Entry<Integer, String> mapElement :

hm.entrySet()) {

Integer key = mapElement.getKey();

// Finding the value

// using getValue() method

String value = mapElement.getValue();

// Printing the key-value pairs

System.out.println(key + " : " + value);

Output

3 : Geeks
2 : For
1 : Geeks

Hashtable in Java
The Hashtable class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. To successfully store and retrieve objects from a
hashtable, the objects used as keys must implement the hashCode method and the equals
method.
import java.util.Enumeration;
import java.util.Hashtable;

public class Main {


public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new Hashtable<>();

// Adding elements to the hashtable


hashtable.put("A", 1);
hashtable.put("B", 2);
hashtable.put("C", 3);
// Getting values from the hashtable
int valueA = hashtable.get("A");
System.out.println("Value of A: " + valueA);
// Removing elements from the hashtable
hashtable.remove("B");
// Enumerating the elements of the hashtable
Enumeration<String> keys = hashtable.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
}
}
}
Output
Value of A: 1
Key: A, Value: 1
Key: C, Value: 3
In conclusion, while the Hashtable class still exists in Java and can still be used, it’s generally
recommended to use the Map interface or one of its implementations instead.
Features of Hashtable
 It is similar to HashMap, but is synchronized.
 Hashtable stores key/value pair in hash table.
 In Hashtable we specify an object that is used as a key, and the value we want to associate
to that key. The key is then hashed, and the resulting hash code is used as the index at
which the value is stored within the table.
 The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
 HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast
Enumeration.
Type Parameters:
 K – the type of keys maintained by this map
 V – the type of mapped values
The Hierarchy of Hashtable

Sorting in Java
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort,
insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use
any kind of algorithms. It is as simple sorting with the help of linear and non-linear data
structures present within java. So there is sorting done with the help of brute force in java
with the help of loops and there are two in-built methods to sort in Java.
Ways of sorting in Java
1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
5. // Java program to demonstrate working of Collections.sort()
6. import java.util.*;
7.
8. public class GFG {
9. public static void main(String[] args)
10. {
11. // Create a list of strings
12. ArrayList<String> al = new ArrayList<String>();
13. al.add("Geeks For Geeks");
14. al.add("Friends");
15. al.add("Dear");
16. al.add("Is");
17. al.add("Superb");
18.
19. /* Collections.sort method is sorting the
20. elements of ArrayList in ascending order. */
21. Collections.sort(al);
22.
23. // Let us print the sorted list
24. System.out.println("List after the use of"
25. + " Collection.sort() :\n" + al);
26. }
27. }
Comparable Interface
The Comparable interface is used to compare an object of the same class with an instance of
that class, it provides ordering of data for objects of the user-defined class. The class has to
implement the java.lang.Comparable interface to compare its instance, it provides the
compareTo method that takes a parameter of the object of that class. In this article, we will
see how we can sort an array of pairs of different data types on the different parameters of
comparison.

Using Comparable Interface

 In this method, we are going to implement the Comparable interface


from java.lang Package in the Pair class.
 The Comparable interface contains the method compareTo to decide the order of the
elements.
 Override the compareTo method in the Pair class.
 Create an array of Pairs and populate the array.
 Use the Arrays.sort() function to sort the array.
 import java.io.*;
 import java.util.*;

 class Pair implements Comparable<Pair> {
 String x;
 int y;

 public Pair(String x, int y)
 {
 this.x = x;
 this.y = y;
 }

 public String toString()
 {
 return "(" + x + "," + y + ")";
 }

 @Override public int compareTo(Pair a)
 {
 // if the string are not equal
 if (this.x.compareTo(a.x) != 0) {
 return this.x.compareTo(a.x);
 }
 else {
 // we compare int values
 // if the strings are equal
 return this.y - a.y;
 }
 }
 }

 public class GFG {
 public static void main(String[] args)
 {

 int n = 4;
 Pair arr[] = new Pair[n];

 arr[0] = new Pair("abc", 3);
 arr[1] = new Pair("a", 4);
 arr[2] = new Pair("bc", 5);
 arr[3] = new Pair("a", 2);

 // Sorting the array
 Arrays.sort(arr);

 // printing the
 // Pair array
 print(arr);
 }

 public static void print(Pair[] arr)
 {
 for (int i = 0; i < arr.length; i++) {
 System.out.println(arr[i]);
 }
 }
 }
Comparator Interface
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.
import java.io.*;
import java.lang.*;
import java.util.*;

// Class 1
// A class to represent a Student
class Student {

// Attributes of a student
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{

// This keyword refers to current instance itself


this.rollno = rollno;
this.name = name;
this.address = address;
}

// Method of Student class


// To print student details in main()
public String toString()
{

// Returning attributes of Student


return this.rollno + " " + this.name + " "
+ this.address;
}
}

// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {

// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{

return a.rollno - b.rollno;


}
}

// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {

// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty ArrayList of Student type


ArrayList<Student> ar = new ArrayList<Student>();

// Adding entries in above List


// using add() method
ar.add(new Student(111, "Mayank", "london"));
ar.add(new Student(131, "Anshul", "nyc"));
ar.add(new Student(121, "Solanki", "jaipur"));
ar.add(new Student(101, "Aggarwal", "Hongkong"));

// Display message on console for better readability


System.out.println("Unsorted");

// Iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));

// Sorting student entries by roll number


Collections.sort(ar, new Sortbyroll());

// Display message on console for better readability


System.out.println("\nSorted by rollno");

// Again iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));

// Sorting student entries by name


Collections.sort(ar, new Sortbyname());

// Display message on console for better readability


System.out.println("\nSorted by name");

// // Again iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Output
Unsorted
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong

Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc

Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur
Properties Class in Java
The Properties class represents a persistent set of properties. The Properties can be
saved to a stream or loaded from a stream. It belongs
to java.util package. Properties define the following instance variable. This variable
holds a default property list associated with a Properties object.
Features of Properties class:
 Properties is a subclass of Hashtable.
 It is used to maintain a list of values in which the key is a string and the value is also a
string i.e; it can be used to store and retrieve string type data from the properties file.
 Properties class can specify other properties list as it’s the default. If a particular key
property is not present in the original Properties list, the default properties will be searched.
 Properties object does not require external synchronization and Multiple threads can share a
single Properties object.
 Also, it can be used to retrieve the properties of the system.
 import java.util.*;
 import java.io.*;
 public class GFG {
 public static void main(String[] args) throws Exception
 {
 // create a reader object on the properties file
 FileReader reader = new FileReader("db.properties");

 // create properties object
 Properties p = new Properties();

 // Add a wrapper around reader object
 p.load(reader);

 // access properties data
 System.out.println(p.getProperty("username"));
 System.out.println(p.getProperty("password"));
 }
 }

You might also like