0% found this document useful (0 votes)
64 views26 pages

Collection Framework 2025

The Java Collection Framework provides a unified architecture for storing and manipulating groups of objects, including various interfaces and classes for different data structures like List, Set, and Map. It allows operations such as searching, sorting, and manipulation of data, with specific methods defined for each interface. The framework includes implementations like ArrayList, HashSet, and LinkedList, which cater to different needs such as order maintenance and element uniqueness.

Uploaded by

swechana07
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)
64 views26 pages

Collection Framework 2025

The Java Collection Framework provides a unified architecture for storing and manipulating groups of objects, including various interfaces and classes for different data structures like List, Set, and Map. It allows operations such as searching, sorting, and manipulation of data, with specific methods defined for each interface. The framework includes implementations like ArrayList, HashSet, and LinkedList, which cater to different needs such as order maintenance and element uniqueness.

Uploaded by

swechana07
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

Collection Framework in Java

Collections in java is a framework that provides an architecture to store and


manipulate the group of objects. All the operations that you perform on a data such as
searching, sorting, insertion, manipulation, deletion etc. can be performed by Java
Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is framework in java

 provides readymade architecture.

 represents set of classes and interface.

 is optional.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group
of objects. It has:

1. Interfaces and its implementations i.e. classes

2. Algorithm

Hierarchy of Collection Framework


Java List Interface

List Interface is the sub interface of Collection. It contains index-based methods to insert and delete
elements. It is a factory of ListIterator interface.

List Interface declaration

1. public interface List<E> extends Collection<E>

Methods of Java List Interface

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> It is used to append all of the elements in the
c) specified collection to the end of a list.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the
list.
void clear() It is used to remove all of the elements from this
list.

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[] 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 It is used to replace all the elements from the list
operator) 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 spliterator() It is used to create spliterator over the elements
in a list.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex) given range.
int size() It is used to return the number of elements
present in the list.

Java List Example

1. import [Link].*;
2. public class ListExample{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Kumar");
8. [Link](1,"Sachin");
9. [Link]("An element at 2nd position: "+[Link](2));
10. for(String s:al){
11. [Link](s);
12. }
13. }
14. }

Output:

An element at 2nd position: Vijay


Amit
Sachin
Vijay
Kumar
Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a

key. Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
LinkedHashMa LinkedHashMap is the implementation of Map. It inherits HashMap
p class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It maintains
ascending order.

Java Map Example: Non-Generic (Old Style)


1. //Non-generic
2. import [Link].*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. [Link](1,"Amit");
8. [Link](5,"Rahul");
9. [Link](2,"Jai");
10. [Link](6,"Amit");
11. //Traversing Map
12. Set set=[Link]();//Converting to Set so that we can traverse
13. Iterator itr=[Link]();
14. while([Link]()){
15. //Converting to [Link] so that we can get key and value separately
16. [Link] entry=([Link])[Link]();
17. [Link]([Link]()+" "+[Link]());
18. }
19. }
20. }

Output:

1 Amit
2 Jai
5 Rahul
6 Amit

Java Map Example: Generic (New Style)


1. import [Link].*;
2. class MapExample2 3. {
4. public static void main(String args[]) 5. {
6. Map<Integer,String> map=new HashMap<Integer,String>();
7. [Link](100,"Amit");
8. [Link](101,"Vijay");
9. [Link](102,"Rahul");
10. //Elements can traverse in any order
11. for([Link] m:[Link]())
12. {
13. [Link]([Link]()+" "+[Link]());
13. }
14. }
15. }

Output:

102 Rahul
100 Amit
101 Vijay

Set Interface
 Set is an interface which extends Collection. It is an unordered collection of objects in which
duplicate values cannot be stored.
 Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
 Set has various methods to add, remove clear, size, etc to enhance the usage of this
interface

// Java code for adding elements in Set

import [Link].*;
public class Set_example
{
public static void main(String[] args)
{
// Set demonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");
[Link]("Set output without the duplicates");

[Link](hash_Set);

// Set deonstration using TreeSet


[Link]("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
[Link](tree_Set);
}
}
(Please note that we have entered a duplicate entity but it is not displayed in the output. Also, we
can directly sort the entries by passing the unordered Set in as the parameter of TreeSet).

Output:
Set output without the duplicates[Set, Example, Geeks, for]
Sorted Set after passing into TreeSet[Example, For, Geeks, Set]

LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

LinkedList class declaration

Let's see the declaration for [Link] class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>,


Clon eable, Serializable

Constructors of Java LinkedList


Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the elements


extends E> c) of the specified collection, in the order, they are
returned by the collection's iterator.

Methods of Java LinkedList


Method Description

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


a list.

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

boolean addAll(Collection<? It is used to append all of the elements in the specified


extends E> c) collection to the end of this list, in the order that they
are returned by the specified collection's iterator.

boolean addAll(Collection<? It is used to append all of the elements in the specified


extends E> c) collection to the end of this list, in the order that they
are returned by the specified collection's iterator.

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

void addFirst(E e) It is used to insert the given element at the beginning


of a list.

void addLast(E e) It is used to append the given element to the end of a


list.
void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.


boolean contains(Object o) It is used to return true if a list contains a specified
element.

Iterator<E> descendingIterator() It is used to return an iterator over the elements in a


deque in reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified


position in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first


occurrence of the specified element, or -1 if the list
does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last


occurrence of the specified element, or -1 if the list
does not contain any element.

ListIterator<E> listIterator(int It is used to return a list-iterator of the elements in


index) proper sequence, starting at the specified position in
the list.
boolean offer(E e) It adds the specified element as the last element of a
list.
boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if


a list is empty.

E peekLast() It retrieves the last element of a list or returns null if a


list is empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or


returns null if a list is empty.

E pollLast() It retrieves and removes the last element of a list, or


returns null if a list is empty.
E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a


list.
E remove() It is used to retrieve and removes the first element of
a list.

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


position in a list.

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


specified element in a list.

E removeFirst() It removes and returns the first element from a list.

boolean It is used to remove the first occurrence of the


removeFirstOccurrence(Object o) specified element in a list (when traversing the list
from head to tail).

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified


removeLastOccurrence(Object o) element in a list (when traversing the list from head
to tail).
E set(int index, E element) It replaces the element at the specified position in a
list with the specified element.

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


in a list in proper sequence (from first to the last
element).
<T> T[] toArray(T[] a) It returns an array containing all the elements in the
proper sequence (from first to the last element); the
runtime type of the returned array is that of the
specified array.

int size() It is used to return the number of elements in a list.

Java LinkedList Example

import [Link].*;
public class LinkedList1
{
public static void main(String args[])
{
LinkedList<String>al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}

Output:
Ravi
Vijay
Ravi
Ajay

Java LinkedList example to add elements Here, we

see different ways to add elements.

import [Link].*;
public class LinkedList2{
public static void main(String args[])
{
LinkedList<String> ll=new LinkedList<String>();
[Link]("Initial list of elements: "+ll);
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("After invoking add(E e) method: "+ll);
//Adding an element at the specific position [Link](1,
"Gaurav");
[Link]("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
[Link]("Sonoo");
[Link]("Hanumat");
//Adding second list elements to the first list
[Link](ll2);
[Link]("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
[Link]("John");
[Link]("Rahul");
//Adding second list elements to the first list at specific position
[Link](1, ll3);
[Link]("After invoking addAll(int index, Collection<? extends E> c) method:
"+ll);
//Adding an element at the first position
[Link]("Lokesh");
[Link]("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
[Link]("Harsh");
[Link]("After invoking addLast(E e) method: "+ll);
}
}

Output:

Initial list of elements: []


After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay] After
invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method: [Ravi,
John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat] After
invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements Here, we

see different ways to remove an element.

import [Link].*;
public class LinkedList3 {

public static void main(String [] args)


{
LinkedList<String> ll=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Anuj");
[Link]("Gaurav");
[Link]("Harsh");
[Link]("Virat");
[Link]("Gaurav");
[Link]("Harsh");
[Link]("Amit");
[Link]("Initial list of elements: "+ll);
//Removing specific element from arraylist
[Link]("Vijay");
[Link]("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
[Link](0);
[Link]("After invoking remove(index) method: "+ll);
LinkedList<String>ll2=new LinkedList<String>(); [Link]("Ravi");
[Link]("Hanumat");
// Adding new elements to arraylist [Link](ll2);
[Link]("Updated list : "+ll);
//Removing all the new elements from arraylist
[Link](ll2);
[Link]("After invoking removeAll() method: "+ll);
//Removing first element from the list
[Link]();
[Link]("After invoking removeFirst() method: "+ll);
//Removing first element from the list
[Link]();
[Link]("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
[Link]("Gaurav");
[Link]("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
[Link]("Harsh");
[Link]("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list


[Link]();
[Link]("After invoking clear() method: "+ll);
}
}

Output:
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit] After
invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit] Updated list : [Ajay,
Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit] After
invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh] After
invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh] After invoking
removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements


import [Link].*;
public class LinkedList4
{
public static void main(String args[])
{

LinkedList<String> ll=new LinkedList<String>();


[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
//Traversing the list of elements in reverse order Iterator
i=[Link](); while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ajay Vijay
Ravi

Java LinkedList Example: Book


import [Link].*;
class Book
{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
[Link] = id;
[Link]=name; [Link] =
author;
[Link] = publisher;
[Link] = quantity;
}
}
public class LinkedListExample
{
public static void main(String[] args)
{
//Creating list of Books
List<Book> list=new LinkedList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to
list [Link](b1);
[Link](b2);
[Link](b3);
//Traversing list
for(Book b:list){
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4 103
Operating System Galvin Wiley 6

Java HashMap class


Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap
class and implements Map interface.

Points to remember
o Java HashMap class contains values based on the key.
o Java HashMap class contains only unique keys.
o Java HashMap class may have one null key and multiple null values.
o Java HashMap class is non synchronized.
o Java HashMap class maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements Map

interface. HashMap class declaration

Let's see the declaration for [Link] class.

1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable,


Serializ able

HashMap class Parameters

Let's see the Parameters for [Link] class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java HashMap class


Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements
extends V> m) of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.

HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.

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.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key
in the map only if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the map.

V compute(K key, BiFunction<? It is used to compute a mapping for the specified


super K,? super V,? extends V> key and its current mapped value (or null if there
remappingFunction) is no current mapping).

V computeIfAbsent(K key, Function<? It is used to compute its value using the given
super K,? extends V> mapping function, if the specified key is not
mappingFunction) already associated with a value (or is mapped to
null), and enters it into this map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key
BiFunction<? super K,? super V,? and its current mapped value if the value for the
extends V> remappingFunction) specified key is present and non-null.

boolean containsValue(Object value) This method returns true if some value equal to
the value exists within the map, else return false.

boolean containsKey(Object key) This method returns true if some key equal to the
key exists within the map, else return false.

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


Map.

void forEach(BiConsumer<? super K,? It performs the given action for each entry in the
super V> action) map until all entries have been processed or the
action throws an exception.

V get(Object key) This method returns the object that contains the
value associated with the key.

V getOrDefault(Object key, V It returns the value to which the specified


defaultValue) key is mapped, or defaultValue if the map
contains no mapping for the key.

boolean isEmpty() This method returns true if the map is empty;


returns false if it contains at least one key.

V merge(K key, V value, BiFunction<? If the specified key is not already associated with
super V,? super V,? extends V> a value or is associated with null, associates it
remappingFunction) with the given non-null value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function
throws an exception.

Collection<V> values() It returns a collection view of the values contained


in the map.

int size() This method returns the number of entries in the


map.
Java HashMap example to add() elements

Here, we see different ways to insert elements.

import [Link].*;
class HashMap1
{
public static void main(String args[])
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
[Link]("Initial list of elements: "+hm);
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");

[Link]("After invoking put() method ");


for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
[Link](103, "Gaurav");
[Link]("After invoking putIfAbsent() method ");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
[Link](104,"Ravi");
[Link](hm);
[Link]("After invoking putAll() method ");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
}
}
Initial list of elements: {}
After invoking put() method
100 Amit
101 Vijay
102 Rahul

After invoking putIfAbsent() method

100 Amit
101 Vijay
102 Rahul
103 Gaurav

After invoking putAll() method

100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi

Java HashMap example to remove() elements

Here, we see different ways to remove elements.

import [Link].*;
public class HashMap2
{
public static void main(String args[])
{
HashMap<Integer,String> map=new HashMap<Integer,String>();
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link](103,"Gaurav");
[Link]("Initial list of elements: "+map);
//key-based removal
[Link](100);
[Link]("Updated list of elements: "+map);
//value-based removal
[Link](101);
[Link]("Updated list of elements: "+map);
//key-value pair based removal
[Link](102, "Rahul");
[Link]("Updated list of elements: "+map);
}
}
Output:
Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {102=Rahul, 103=Gaurav}
Updated list of elements: {103=Gaurav}

Java HashMap example to replace()

elements Here, we see different ways to replace

elements.

import [Link].*;
class HashMap3
{
public static void main(String args[])
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]("Initial list of
elements:");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
[Link]("Updated list of elements:");
[Link](102, "Gaurav");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
[Link]("Updated list of elements:");
[Link](101, "Vijay", "Ravi");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
[Link]("Updated list of elements:");
[Link]((k,v) -> "Ajay");
for([Link] m:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
}
}
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay

TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java
that 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 set creation time, depending on which constructor
is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
Few important features of TreeSet are as follows:
1. TreeSet implements the SortedSet interface so duplicate values are not allowed.
2. Objects in a TreeSet are stored in a sorted and ascending order.
3. TreeSet does not preserve the insertion order of elements but elements are sorted by
keys.
4. TreeSet does not allow to insert Heterogeneous objects. It will throw
classCastException at Runtime if trying to add hetrogeneous objects.
5. TreeSet serves as an excellent choice for storing large amounts of sorted
information which are supposed to be accessed quickly because of its faster
access and retrieval time.
6. TreeSet is basically implementation of a self-balancing binary search tree like Red-
Black Tree. Therefore operations like add, remove and search take O(Log n) time.
And operations like printing n elements in sorted order takes O(n) time.

Constructors of TreeSet class:


1. TreeSet t = new TreeSet();
This will create empty TreeSet object in which elements will get stored in default
natural sorting order.
2. TreeSet t = new TreeSet(Comparator comp);
This constructor is used when external specification of sorting order of elements is
needed.
3. TreeSet t = new TreeSet(Collection col);
This constructor is used when any conversion is needed from any Collection object
to TreeSet object.
4. TreeSet t = new TreeSet(SortedSet s);
This constructor is used to convert SortedSet object to TreeSet Object.
Synchronized TreeSet:
The implementation in a TreeSet is not synchronized in a sense that if multiple threads
access a tree set concurrently, and at least one of the threads modifies the set, it must be
synchronized externally. This is typically accomplished by synchronizing on some object
that naturally encapsulates the set. If no such object exists, the set should be “wrapped”
using the [Link] method. This is best done at creation time,
to prevent accidental unsynchronized access to the set:

TreeSet ts = new TreeSet();


Set syncSet = [Link](ts);
Below program illustrates the basic opearation of a TreeSet:
// Java program to demonstrate insertions in
TreeSet import [Link].*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();
// Elements are added using
add() method [Link]("A");
[Link]("B");
[Link]("C");
// Duplicates will not get
insert [Link]("C");
// Elements get stored in default naturalSorting Order(Ascending)
[Link](ts1);
}
}
Output:

[A,B,C]

Java StringTokenizer Class


StringTokenizer class in Java is used to break a string into tokens based on delimiters.
A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters processed.

 A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
 It provides the first step in the parsing process often called lexer or scanner.
 It implements the Enumeration interface.
 To perform Java String Tokenization, we need to specify an input string and a set of
delimiters.
 A delimiter is a character or set of characters that separate tokens in the string.
Note: StringTokenizer is a legacy class, and the split() method is preferred for modern
applications.
Example: Below is a simple example that explains the use of Java StringTokenizer to
split a space-separated string into tokens:

// Demonstration of Java StringTokenizer

import [Link];
public class Geeks {
public static void main(String[] args)
{
// Input string
String s = "Hello Geeks how are you";
// Create a StringTokenizer object with space as the delimiter
StringTokenizer st = new StringTokenizer(s, " ");

// Tokenize the string and print each token


while ([Link]())
{
[Link]([Link]());
}
}
}

Output
Hello
Geeks
how
are
you

Date class in Java (With Examples)


The class Date represents a specific instant in time, with millisecond
precision. The Date class of [Link] package implements
Serializable, Cloneable and Comparable interface. It provides
constructors and methods to deal with date and time with java.
Constructors
 Date() : Creates date object representing current date and time.
 Date(long milliseconds) : Creates a date object for the given
milliseconds since January 1, 1970, [Link] GMT.
 Date(int year, int month, int date)
 Date(int year, int month, int date, int hrs, int min)
 Date(int year, int month, int date, int hrs, int min, int sec)
 Date(String s)
Note : The last 4 constructors of the Date class are Deprecated.

// Java program to demonstrate constuctors of Date


import [Link].*;

public class Main


{
public static void main(String[] args)
{
Date d1 = new Date();
[Link]("Current date is " + d1);
Date d2 = new Date(2323223232L);
[Link]("Date represented is "+ d2 );
}
}

Output:
Current date is Tue Jul 12 [Link] IST 2016
Date represented is Wed Jan 28 [Link] IST 1970

[Link] class in Java


Random class is used to generate pseudo-random numbers in java. An instance of this
class is thread-safe. The instance of this class is however cryptographically insecure.
This class provides various method calls to generate different random data types such
as float, double, int.
Constructors:
 Random(): Creates a new random number generator
 Random(long seed): Creates a new random number generator using a single long seed

// Java program to demonstrate


// method calls of Random class
import [Link];

public class Test


{
public static void main(String[] args)
{
Random random = new Random();
[Link]([Link](10));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
byte[] bytes = new byte[10];
[Link](bytes);
[Link]("[");
for(int i = 0; i< [Link]; i++)
{
[Link]("%d ", bytes[i]);
}
[Link]("]\n");

[Link]([Link]());
[Link]([Link]());
long seed = 95;
[Link](seed);

// Note: Running any of the code lines below


// will keep the program running as each of the
// methods below produce an unlimited random
// values of the corresponding type

/* [Link]("Sum of all the elements in the IntStream returned = " +


[Link]().count());
[Link]("Count of all the elements in the DoubleStream returned = " +
[Link]().count());
[Link]("Count of all the elements in the LongStream returned = " +
[Link]().count());

*/

}
}

Output:
4
true
0.19674934340402916
0.7372021
1.4877581394085997
[-44 75 68 89 81 -72 -1 -66 -64 117 ]
158739962004803677
-1344764816

Scanner Class(Java User Input)

The Scanner class is used to get user input, and it is found in the [Link] package.

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use the
nextLine() method, which is used to read Strings:

Example
import [Link]; // Import the Scanner class

class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner([Link]); // Create a Scanner object
[Link]("Enter username");

String userName = [Link](); // Read user input


[Link]("Username is: " + userName); // Output user input
}
}

You might also like