0% found this document useful (0 votes)
18 views77 pages

Unit 4 Collections

The document provides an overview of the Java Collections Framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes such as List, Set, and Queue. It details the Collection interface, its methods, and specific implementations like ArrayList, LinkedList, and Vector, along with their functionalities. Additionally, it covers the Stack data structure and its operations, emphasizing the framework's role in enhancing code efficiency and readability.

Uploaded by

shreygupta979
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)
18 views77 pages

Unit 4 Collections

The document provides an overview of the Java Collections Framework, which allows for the storage and manipulation of groups of objects through various interfaces and classes such as List, Set, and Queue. It details the Collection interface, its methods, and specific implementations like ArrayList, LinkedList, and Vector, along with their functionalities. Additionally, it covers the Stack data structure and its operations, emphasizing the framework's role in enhancing code efficiency and readability.

Uploaded by

shreygupta979
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

Collections In Java

What is Collection?

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


• Any group of individual objects which are represented as a single unit
is known as the collection of the objects.
Collections in Java

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


store and manipulate a group of objects.
• Java Collections can achieve all the operations that we perform on
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 a framework?

• A framework provides a ready-made structure of classes and


interfaces for building software applications efficiently. It simplifies
adding new features by offering reusable components that perform
similar tasks, eliminating the need to create a framework from scratch
for each new project. This approach enhances object-oriented design,
making development quicker, more consistent, and reliable.
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
What is the Collection Framework?

• The Collection framework represents a unified architecture for storing


and manipulating a group of objects. It enhances code efficiency and
readability by offering various data structures, including arrays, linked
lists, trees, and hash tables, tailored to different programming needs.
It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Hierarchy of Collection Framework
The hierarchy of Collection framework. The java.util package contains all the classes and interfaces for
the Collection framework.
Iterator Interface

• The iterator interface provides the facility of iterating the elements in


a forward direction only.
Method Description
public boolean hasNext() It returns true if the iterator has more
elements; otherwise, it returns false.

public Object next() It returns the element and moves the


cursor pointer to the next element.

public void remove() It removes the last elements returned by


the iterator. It is less used.
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 the
Collection interface also implement the Iterable interface.
• It contains only one abstract method. i.e.,
• Example:
Iterator<T> iterator()
Collection Interface

• The Collection interface is the interface which is


implemented by all the classes in the collection
framework. It declares the methods that every
collection will have. In other words, we can say that
the Collection interface builds the foundation on
which the collection framework depends.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No. Method Description


1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<? extends E> c) It is used to insert the specified collection elements
in the invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.

4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified
collection from the invoking collection.

5 default boolean removeIf(Predicate<? super E> It is used to delete all the elements of the collection
filter) that satisfy the specified predicate.

6 public boolean retainAll(Collection<?> c) It is used to delete all the elements of invoking


collection except the specified collection.

By Ajai Kumar Maurya CSE Mob: 9335833415


Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No. Method Description

7 public int size() It returns the total number of elements in the


collection.
8 public void clear() It removes the total number of elements from the
collection.
9 public boolean contains(Object element) It is used to search an element.

10 public boolean containsAll(Collection<?> c) It is used to search the specified collection in the


collection.
11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.


13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
type of the returned array is that of the specified
array.

By Ajai Kumar Maurya CSE Mob: 9335833415


Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No. Method Description


14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as
its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in
the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.

By Ajai Kumar Maurya CSE Mob: 9335833415


Java List

• List in Java provides the facility to maintain the ordered collection. It


contains the index-based methods to insert, update, delete and
search the elements. It can have the duplicate elements also. We can
also store the null elements in the list.
• The List interface is found in the java.util package and inherits the
Collection interface. It is a factory of ListIterator interface. Through
the ListIterator, we can iterate the list in forward and backward
directions. The implementation classes of List interface are ArrayList,
LinkedList, Stack, and Vector. The ArrayList and LinkedList are widely
used in Java programming. The Vector class is deprecated
Java List Class Methods
Method Description

void add(int index, E element) It is used to insert the specified element at the
specified position in a list.

boolean add(E e) It is used to append the specified element at the


end of a list.

boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the
specified collection to the end of a list.

boolean addAll(int index, Collection<? extends E> It is used to append all the elements in the
c) specified collection, starting at the specified
position of the list.

void clear() It is used to remove all of the elements from this


list.
Method Description

boolean equals(Object o) It is used to compare the specified object with the


elements of a list.

int hashcode() It is used to return the hash code value for a list.

E get(int index) It is used to fetch the element from the particular


position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.

Object[] toArray() It is used to return an array containing all of the


elements in this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the


elements in this list in the correct order.
boolean contains(Object o) It returns true if the list contains the specified
element

boolean containsAll(Collection<?> c) It returns true if the list contains all the specified
element

int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.

E remove(int index) It is used to remove the element present at the


specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the


specified element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

void replaceAll(UnaryOperator<E> operator) It is used to replace all the elements from the list with
the specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.
E set(int index, E element) It is used to replace the specified element in
the list, present at the specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the
basis of specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the elements in


a list.

List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the
given range.

int size() It is used to return the number of elements


present in the list.
Example:
import java.util.*; list.add("Grapes");
public class Main{ //Iterating the List element usi
public static void main ng for-each loop
(String args[]){ for(String fruit:list)
//Creating a List System.out.println(fruit);
List<String> list=new ArrayList
<String>(); }
//Adding elements in the List }
list.add("Mango");
list.add("Apple");
list.add("Banana");
Java ArrayList
• ArrayList in Java is a dynamic array implementation that belongs to
the Java Collections Framework. This is a big array that grows on its
own as more elements are added to it.
• The ArrayList in Java can also have duplicate elements. It implements
the List interface so that we can use all the methods of the List
interface here. The ArrayList maintains the insertion order internally.
Example:
import java.util.*; System.out.println("Returning ele
public class Main{ ment: "+al.get(1));//it will return t
he 2nd element, because index sta
public static void main(String args[ rts from 0
]){
//changing the element
ArrayList<String> al=new ArrayList
<String>(); al.set(1,"Dates");
al.add("Mango"); //Traversing list
al.add("Apple"); for(String fruit:al)
al.add("Banana"); System.out.println(fruit);
al.add("Grapes");
//accessing the element }
}
LinkedList
The LinkedList class is a collection which can contain many objects of the same type, just like

the ArrayList.

The LinkedList class has all of the same methods as the ArrayList class because they both implement

the List interface. This means that you can add items, change items, remove items and clear the list in the

same way.
How the LinkedList works
The LinkedList stores its items in "containers." The list has a link to the first container and

each container has a link to the next container in the list. To add an element to the list, the

element is placed into a new container and that container is linked to one of the other

containers in the list.


LinkedList Methods
Method Description

addFirst() Adds an item to the beginning of the list

addLast() Add an item to the end of the list

removeFirst() Remove an item from the beginning of the list

removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list

getLast() Get the item at the end of the list


Program 1
import java.util.*;

public class LinkListPro {


public static void main(String[] args) {
LinkedList<String> student = new LinkedList<String>();
student.add(“Raman");
student.add(“Kamal");
student.add(“Vikash");

// Use addFirst() to add the item to the beginning


student.addFirst(“Arvind");
System.out.println(student);
}
}
Java Vector
• Vector is like the dynamic array which can grow or shrink its size. Unlike
array, we can store n-number of elements in it as there is no size limit. It is
a part of Java Collection framework since Java 1.2. It is found in
the java.util package and implements the List interface, so we can use all
the methods of List interface here.
• It is recommended to use the Vector class in the thread-safe
implementation only. If you don't need to use the thread-safe
implementation, you should use the ArrayList, the ArrayList will perform
better in such case.

It is similar to the ArrayList, but with two differences-


• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a
collections framework.
Example
import java.util.*; //Display Vector elements again
public class Main { System.out.println("Elements are: "+vec);
public static void main(String args[]) { //Checking if Tiger is present or not in this vector
//Create an empty vector with initial capacity 4 if(vec.contains("Tiger"))
Vector<String> vec = new Vector<String>(4); {
//Adding elements to a vector System.out.println("Tiger is present at the index " +vec.indexOf("Tig
er"));
vec.add("Tiger");
}
vec.add("Lion");
else
vec.add("Dog");
{
vec.add("Elephant");
System.out.println("Tiger is not present in the list.");
//Check size and capacity
}
System.out.println("Size is: "+vec.size());
//Get the first element
System.out.println("Default capacity is: "+vec.capacity());
System.out.println("The first animal of the vector is = "+vec.firstEleme
//Display Vector elements nt());
System.out.println("Vector element is: "+vec); //Get the last element
vec.addElement("Rat"); System.out.println("The last animal of the vector is = "+vec.lastElemen
vec.addElement("Cat"); t());

vec.addElement("Deer"); }

System.out.println("Size after addition: "+vec.size()); }

System.out.println("Capacity after addition is: "+vec.capacity());


Java Stack
Java Stack
The stack is a linear data structure that is used to

store the collection of objects. It is based on Last-

In-First-Out (LIFO). Java

collection framework provides many interfaces

and classes to store the collection of objects. One

of them is the Stack class that provides different

operations such as push, pop, search, etc.


Java Stack
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the
stack.
Java Stack
Let's remove (pop) 18, 45, and 11 from the stack.
Creating a Stack
If we want to create a stack, first, import the java.util package and
create an object of the Stack class.

1.Stack stk = new Stack();

Or

1.Stack<type> stk = new Stack<>();


Creating a Stack
Method Modifier and Type Method Description
empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the


top of the stack.
pop() E The method removes an element from the top of
the stack and returns the same element as the
value of that function.

peek() E The method looks at the top element of the stack


without removing it.

search(Object o) int The method searches the specified object and


returns the position of the object. Object not found
it return -1.
Stack Program1
import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
Stack Program2
import java.util.Stack;
public class StackPeekMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
// pushing elements into Stack
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
stk.push("Orange");
System.out.println("Stack: " + stk);
// Access element from the top of the stack
String fruits = stk.peek();
//prints stack
System.out.println("Element at top: " + fruits);
}
}
Java Queue
Interface
Java Queue
The interface Queue is available in the java.util package and does extend the

Collection interface. It is used to keep the elements that are processed in the First In

First Out (FIFO) manner. It is an ordered list of objects, where insertion of elements

occurs at the end of the list, and removal of elements occur at the beginning of the list.

public interface Queue<E> extends Collection<E>


Java Queue
Method Description
boolean add(object) It is used to insert the specified element into this
queue and return true upon success.
boolean offer(object) It is used to insert the specified element into this
queue.
Object remove() It is used to retrieves and removes the head of
this queue.
Object poll() It is used to retrieves and removes the head of
this queue, or returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the
head of this queue.
Object peek() It is used to retrieves, but does not remove, the
head of this queue, or returns null if this queue is
empty.
Java Queue
Features of a Queue
The following are some important features of a queue.
1. As discussed earlier, FIFO concept is used for insertion and deletion of elements from a queue.
2. The Java Queue provides support for all of the methods of the Collection interface including
deletion, insertion, etc.
3. PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are used most
frequently.
4. The NullPointerException is raised, if any null operation is done on the BlockingQueues.
5. Those Queues that are present in the util package are known as Unbounded Queues.
6. Those Queues that are present in the util.concurrent package are known as bounded Queues.
7. All Queues barring the Deques facilitates removal and insertion at the head and tail of the queue;
respectively. In fact, deques support element insertion and removal at both ends.
Java Queue

PriorityQueue Class

PriorityQueue is also class that is defined in the collection framework that gives us a

way for processing the objects on the basis of priority. It is already described that the

insertion and deletion of objects follows FIFO pattern in the Java queue. However,

sometimes the elements of the queue are needed to be processed according to the

priority, that's where a PriorityQueue comes into action.

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializ


able
Queue Program 1
import java.util.*;
class TestCollection12{ while(itr.hasNext()){
public static void main(String args[]){ System.out.println(itr.next());
PriorityQueue<String> queue=new PriorityQueue
}
<String>();
queue.add("Amit"); queue.remove();
queue.add("Vijay"); queue.poll();
queue.add("Karan");
queue.add("Jai"); System.out.println("after removing tw
queue.add("Rahul"); o elements:");
System.out.println("head:"+queue.element()); Iterator<String> itr2=queue.iterator();
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:" while(itr2.hasNext()){
); System.out.println(itr2.next());
Iterator itr=queue.iterator();
Methods of Java Deque Interface
Method Description
boolean add(object) It is used to insert the specified element into this deque and return true upon success.

boolean offer(object) It is used to insert the specified element into this deque.

Object remove() It is used to retrieve and removes the head of this deque.

Object poll() It is used to retrieve and removes the head of this deque, or returns null if this deque is empty.

Object element() It is used to retrieve, but does not remove, the head of this deque.

Object peek() It is used to retrieve, but does not remove, the head of this deque, or returns null if this deque is empty.

Object peekFirst() The method returns the head element of the deque. The method does not remove any element from the
deque. Null is returned by this method, when the deque is empty.

Object peekLast() The method returns the last element of the deque. The method does not remove any element from the
deque. Null is returned by this method, when the deque is empty.

Boolean offerFirst(e) Inserts the element e at the front of the queue. If the insertion is successful, true is returned; otherwise,
false.

Object offerLast(e) Inserts the element e at the tail of the queue. If the insertion is successful, true is returned; otherwise,
false.
Set in Java
Set In Java
The set is an interface available in the java.util package. The set interface extends

the Collection interface. An unordered collection or list in which duplicates are not

allowed is referred to as a collection interface.

Set<Type> obj=new LinkListHasSet<Type>();


Operations on the Set Interface
On the Set, we can perform all the basic mathematical operations like intersection,
union and difference.
Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2,
83, 45, 3, 12, 55]. We can perform the following operation on the Set:
• Intersection: The intersection operation returns all those elements which are
present in both the set. The intersection of set1 and set2 will be [33, 45, 55].
• Union: The union operation returns all the elements of set1 and set2 in a single set,
and that set can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12,
22, 33, 34, 45, 55, 66, 77, 83].
• Difference: The difference operation deletes the values from the set which are
present in another set. The difference of the set1 and set2 will be [66, 34, 22, 77].
Operations on the Set Interface
In set, addAll() method is used to perform the union, retainAll() method is used to

perform the intersection and removeAll() method is used to perform difference.

Let's take an example to understand how these methods are used to perform the

intersection, union, and difference operations.


Set Program1
import java.util.*;
public class setExample{
public static void main(String[] args)
{
// creating LinkedHashSet using the Set
Set<String> data = new LinkedHashSet<Stri
ng>();

data.add("JavaTpoint");
data.add("Set");
data.add("Example");
data.add("Set");

System.out.println(data);
}
}
Set Program2
import java.util.*;
public class SetOperations
{ // Finding Intersection of set1 and set2
public static void main(String args[]) Set<Integer> intersection_data = new HashSet<I
{ nteger>(set1);
Integer[] A = {22, 45,33, 66, 55, 34, 77}; intersection_data.retainAll(set2);
Integer[] B = {33, 2, 83, 45, 3, 12, 55}; System.out.print("Intersection of set1 and set2 is:")
Set<Integer> set1 = new HashSet<Integer>(); ;
System.out.println(intersection_data);
set1.addAll(Arrays.asList(A));
Set<Integer> set2 = new HashSet<Integer>(); // Finding Difference of set1 and set2
Set<Integer> difference_data = new HashSet<Int
set2.addAll(Arrays.asList(B)); eger>(set1);
difference_data.removeAll(set2);
// Finding Union of set1 and set2 System.out.print("Difference of set1 and set2 is:");
Set<Integer> union_data = new HashSet<Inte
ger>(set1); System.out.println(difference_data);
union_data.addAll(set2); }
System.out.print("Union of set1 and set2 is:"); }

System.out.println(union_data);
HashSet in Java
HashSet In Java
Java HashSet class is used to create a collection that uses a hash table for storage. It

inherits the AbstractSet class and implements Set interface.


The important points about Java HashSet class are:
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here, elements are inserted
on the basis of their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16, and the load factor is 0.75.

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable


Constructors of Java HashSet class
SN Constructor Description
1) HashSet() It is used to construct a default HashSet.
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given
integer value capacity. The capacity grows automatically as
elements are added to the HashSet.

3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given
loadFactor) integer value capacity and the specified load factor.
4) HashSet(Collection<? extends E> It is used to initialize the hash set by using the elements of the
c) collection c.
Constructors of Java HashSet class
SN Modifier & Type Method Description
1) boolean add(E e) It is used to add the specified element to this set if it is not already
present.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.

4) boolean contains(Object o) It is used to return true if this set contains the specified element.

5) boolean isEmpty() It is used to return true if this set contains no elements.


6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.
7) boolean remove(Object o) It is used to remove the specified element from this set if it is
present.
8) int size() It is used to return the number of elements in the set.
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over the
elements in the set.
HashSet Program1
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
HashSet Program2
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
HashMap
Java HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as

well, but there should be only one null key object and there can be any number of null values. This class

makes no guarantees as to the order of the map. To use this class and its methods, you need to

import java.util.HashMap package or its superclass.

Method Method

1. get() 5. keySet()

2. remove() 6. values()

3. clear()
4. size()
Methods of Java HashMap Class

Method Description
void clear() It is used to remove all of the mappings from this
map.
boolean isEmpty() It is used to return true if this map contains no key-
value mappings.

Object clone() It is used to return a shallow copy of this HashMap


instance: the keys and values themselves are not
cloned.

Set entrySet() It is used to return a collection view of the


mappings contained in this map.

Set keySet() It is used to return a set view of the keys contained


in this map.
V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.
Program 2
import java.util.HashMap;
public class Main
{
public static void main(String[] args)
{
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and
values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}
Program 3 Use KeySet()
import java.util.HashMap;
public class Main
{
public static void main(String[] args)
{
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and
values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
}
Program 4 Use values()
import java.util.HashMap;
public class Main
{
public static void main(String[] args)
{
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and
values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
for (String i : capitalCities.values()) {
System.out.println(i);
}
}
Program 4 Use get()
import java.util.HashMap;
public class Main
{
public static void main(String[] args)
{
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and
values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
for (String i : capitalCities.values()) {
System.out.println(“Key: “+i+”Value: “+capilatalCities.get(i));

}
}
Write a program in java use collection
create HasMap of people , and set name
of people and their age and print the
data.
Program 5 Use get()
// Import the HashMap class
import java.util.HashMap;

public class PeopleInfo {


public static void main(String[] args) {

// Create a HashMap object called people


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

// Add keys and values (Name, Age)


people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);

for (String i : people.keySet()) {


System.out.println("Name: " + i + " Age: " + people.get(i));
}
}
}
Tree Map in Java
Tree Map In Java
Java TreeMap class is a red-black tree based implementation. It provides an
efficient means of storing key-value pairs in sorted order.
The important points about Java TreeMap class are:
• Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have multiple null values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.

public class TreeMap<K,V> extends AbstractMap<K,V> implements Navigabl


eMap<K,V>, Cloneable, Serializable
Tree Map In Java
TreeMap class Parameters
Let's see the Parameters for java.util.TreeMap class.
•K: It is the type of keys maintained by this map.
•V: It is the type of mapped values.
Tree Map In Java
Constructors of Java TreeMap class

Constructor Description
It is used to construct an empty tree map that will be sorted
TreeMap()
using the natural order of its key.

TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be
comparator) sorted using the comparator comp.

TreeMap(Map<? extends K,? extends It is used to initialize a treemap with the entries from m,
V> m) which will be sorted using the natural order of the keys.

TreeMap(SortedMap<K,? extends V> It is used to initialize a treemap with the entries from the
m) SortedMap sm, which will be sorted in the same order as sm.
TreeMap Program1
1.import java.util.*;
2.class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMa
p<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9.
10. for(Map.Entry m:map.entrySet()){
11. System.out.println(m.getKey()+" "+m.getV
alue());
12. }
13. }
14.}
TreeMap Program2
1.import java.util.*; 14. map.remove(102);
2.public class TreeMap2 { 15. System.out.println("After invokin
3. public static void main(String args[]) { g remove() method");
4. TreeMap<Integer,String> map=new TreeMa 16. for(Map.Entry m:map.entrySet()
p<Integer,String>(); )
5. map.put(100,"Amit"); 17. {
6. map.put(102,"Ravi"); 18. System.out.println(m.getKey()
7. map.put(101,"Vijay"); +" "+m.getValue());
8. map.put(103,"Rahul"); 19. }
9. System.out.println("Before invoking remove 20. }
() method"); 21. }
10. for(Map.Entry m:map.entrySet())
11. {
12. System.out.println(m.getKey()+" "+m.get
Value());
13. }
Java Comparator

• 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).
• It provides multiple sorting sequences, i.e., you can sort the elements
on the basis of any data member, for example, rollno, name, age or
anything else.
Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, Object It compares the first object with the
obj2) second object.

public boolean equals(Object obj) It is used to compare the current object


with the specified object.

public boolean equals(Object obj) It is used to compare the current object


with the specified object.
Age Comparator
import java.util.*; Name Comparator
class AgeComparator implements Comp
arator{
import java.util.*;
public int compare(Object o1,Object o2)
{ class NameComparator implements Co
mparator<Student>{
Student s1=(Student)o1;
public int compare(Student s1,Student s
Student s2=(Student)o2; 2){
return s1.name.compareTo(s2.name);
if(s1.age==s2.age) }
return 0; }
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
Comparable Interface in Java

• Java Comparable interface is used to order the objects of the user-


defined class. This interface is found in java.lang package and contains
only one method named compareTo(Object). It provides a single
sorting sequence only, i.e., you can sort the elements on the basis of
single data member only. For example, it may be rollno, name, age or
anything else.
compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current


object with the specified object. It returns
• positive integer, if the current object is greater than the specified
object.
• negative integer, if the current object is less than the specified object.
• zero, if the current object is equal to the specified object.
class Student implements Comparable public int compareTo(Student st){
<Student>{ if(age==st.age)
int rollno; return 0;
String name; else if(age>st.age)
int age; return 1;
Student(int rollno,String name,int age){ else
this.rollno=rollno; return -1;
this.name=name; }
this.age=age; }
}
Comparable Vs. Comparator in Java

Comparable Comparator
• It defines natural • It defines custom sorting logic
ordering within a class. • It is implemented in a separate
• It is implemented inside the class or using lambda
class being sorted. expressions.
• It uses the compareTo() method. • It uses the compare() method.
• It allows sorting by one one. • It allows sorting by multiple
criteria.
Properties class in Java

• The properties object contains key and value pair both as a string.
The java.util.Properties class is the subclass of Hashtable.
• It can be used to get property value based on the property key. The
Properties class provides methods to get data from the properties file
and store data into the properties file. Moreover, it can be used to get
the properties of a system.
An Advantage of the properties file
• Recompilation is not required if the information is changed from a
properties file: If any information is changed from the properties file,
you don't need to recompile the java class. It is used to store
information which is to be changed frequently.
Constructors of Properties class

Method Description
Properties() It creates an empty property list with no default
values.

Properties(Properties defaults) It creates an empty property list with the specified


defaults.
Methods of Properties class
The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) It loads data from the Reader object.

public void load(InputStream is) It loads data from the InputStream object

public void loadFromXML(InputStream in) It is used to load all of the properties represented by the XML
document on the specified input stream into this properties table.

public String getProperty(String key) It returns value based on the key.

public String getProperty(String key, String defaultValue) It searches for the property with the specified key.

public void setProperty(String key, String value) It calls the put method of Hashtable.

public void list(PrintStream out) It is used to print the property list out to the specified output stream.

public void list(PrintWriter out)) It is used to print the property list out to the specified output stream.

public Enumeration<?> propertyNames()) It returns an enumeration of all the keys from the property list.

You might also like