0% found this document useful (0 votes)
2 views64 pages

Java Collections

Uploaded by

Pratyush Sharma
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)
2 views64 pages

Java Collections

Uploaded by

Pratyush Sharma
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

Java Collections

The Java Collections API provide Java developers with a set of classes and interfaces that
makes it easier to work with collections of objects, e.g. lists, maps, stacks etc.

Rather than having to write your own collection classes, Java provides these ready-to-
use collection classes for you.

Array :

1. An array is an indexed collection of fixed no of homogeneous data elements.

2. An array represents a group of elements of same data type.

3. The main advantage of array is we can represent huge no of elements by using single variable. So that
readability of the code will be improved.

 Example Without Arrays


int mark1 = 90;
int mark2 = 85;
int mark3 = 92;
int mark4 = 78;
int mark5 = 88;
 Example Without Arrays

int[] mark = {90,85,92,78,88};

Limitation of Object[] array :


1. Arrays are fixed in size that is once we created an array there is no chance of increasing (or)
decreasing the size based on our requirement hence to use arrays concept compulsory we should know
the size in advance which may not possible always.

2. Arrays can hold only homogeneous data elements.

Student[] s = new Student[10000]; // Array to hold Student objects


s[0] = new Student(); // Valid, because Student is the correct type
s[1] = new Customer(); // Invalid, results in a compile-time error

3) But we can resolve this problem by using object type array(Object[]).


// Create an array of type Object
Object[] o = new Object[10000];

// Store a Student object in the array


o[0] = new Student("Alice", 20);

// Store a Customer object in the array


o[1] = new Customer("C123", "123 Main St");

// Access and print the elements


[Link](o[0]); // Prints Student object
[Link](o[1]); // Prints Customer object
4) Arrays concept is not implemented based on some data structure hence ready-made methods
support we can't expert. For every requirement we have to write the code explicitly.

To overcome the above limitations we should go for collections concept.

1. Collections are growable in nature that is based on our requirement we can increase (or) decrease the
size hence memory point of view collections concept is recommended to use.

2. Collections can hold both homogeneous and heterogeneous objects.

3. Every collection class is implemented based on some standard data structure hence for every
requirement ready-made method support is available being a programmer we can use these methods
directly without writing the functionality on our own.
ArrayList<Object> list = new ArrayList<>();
[Link](new Student("Alice", 20));
[Link](new Customer("C123", "123 Main St"));

Differences between Arrays and Collections ?

ARRAYS COLLECTIONS
1) Fixed in size. 1. Collections are growable in nature.
2) Memory point of view arrays are not 2. Memory point of view collections are
recommended to use. highly recommended to use.
3) Performance point of view arrays are 3. Performance point of view collections are
recommended to use not recommended to use.
4) Arrays can hold only homogeneous data type 4. Collections can hold both homogeneous
elements. and heterogeneous elements.
5) There is no underlying data structure for 5. Every collection class is implemented
arrays and hence there is no readymade based on some standard data structure
method support. and hence readymade method support is
available.
6) Arrays can hold both primitives and object 6. Collections can hold only objects but not
types. primitives.

Collection:
If we want to represent a group of objects as single entity then we should go for collections.

Collection framework:

It defines several classes and interfaces to represent a group of objects as a single entity.

Java Collection Core Classes and Interfaces :

The core interfaces of the Java Collection API are:

 Java Collection
 Java List
 Java Set
 Java SortedSet
 Java navigableSet
 Java Map
 Java SortedMap
 Java NavigableMap
 Java Queue

Collection
1. If we want to represent a group of "individual objects" as a single entity then we should go for
collection.
2. In general we can consider collection as root interface of entire collection framework.

3. Collection interface defines the most common methods which can be applicable for any collection
object.

4. There is no concrete class which implements Collection interface directly.

See Example Student :

JAVA COLLECTION HIERARCHY

List :
1. It is the child interface of Collection.

2. If we want to represent a group of individual objects as a single entity where "duplicates are allow and
insertion order must be preserved" then we should go for List interface
SET :
1. It is the child interface of Collection.

2. If we want to represent a group of individual objects as single entity "where duplicates are not allow
and insertion order is not preserved" then we should go for Set interface.
SORTED SET :
1. It is the child interface of Set.

2. If we want to represent a group of individual objects as single entity "where duplicates are not allow
but all objects will be insertion according to some sorting order then we should go for SortedSet. (or)

3. If we want to represent a group of "unique objects" according to some sorting order then we should
go for SortedSet.

NavigableSet:

1. It is the child interface of SortedSet.

2. It provides several methods for navigation purposes.

Queue:

1. It is the child interface of Collection.

2. If we want to represent a group of individual objects prior to processing then we should go for queue
concept
Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and Queue) meant for
representing a group of individual objects. If we want to represent a group of objects as key-value pairs
then we should go for Map.

Map:

1. Map is not child interface of Collection.

2. If we want to represent a group of objects as key-value pairs then we should go for Map interface.

3. Duplicate keys are not allowed but values can be duplicated.

SortedMap:

1. It is the child interface of Map.


2. If we want to represent a group of objects as key value pairs "according to some sorting order of keys"
then we should go for SortedMap.

NavigableMap:

1) It is the child interface of SortedMap and defines several methods for navigation purposes.

Java Collections Class :


 addAll()
 binarySearch()
 copy()
 reverse()
 shuffle()
 sort()
 copy()
 min()
 max()
 replaceAll()
 unmodifiableSet()

The Java Collections class, [Link], contains a long list of utility methods for
working with collections in Java.

addAll()

The Java Collections addAll() method can add a variable number of elements to
a Collection (typically either a List or a Set . Here is a java code example of calling
the Collections addAll() method:

List<String> list = new ArrayList<>();

[Link](list, "element 1", "element 2", "element 3");

binarySearch()

The Collections binarySearch() method can search a Java List for an element using a binary search
algorithm. The List must be sorted in ascending order before you search it using binarySearch() . See the
tutorial about sorting Java Lists for more information about how to sort a List in ascending order. Here is
an example of searching a List using the Collections binarySearch() method:

copy()

The Collections copy() method can copy all elements of a List into another List. Here is a Java
example of calling the Collections copy() method:

List<String> source = new ArrayList<>();


[Link](source, "e1", "e2", "e3");

List<String> destination = new ArrayList<>();


[Link](destination, source);

reverse()

The Collections reverse() method can reverse the elements in a Java List.
Here is an example of reversing the elements of a List:

List>String< list = new ArrayList<String>();

[Link]("one");
[Link]("two");
[Link]("three");

[Link](list);

After executing the above code, the sequence of the elements in the List will
be three, two, one .

shuffle()

The Collections shuffle() method can shuffle the elements of a List. Here is an example of
shuffling a list with the Collections shuffle() method:

List>String< list = new ArrayList<String>();


[Link]("one");
[Link]("two");
[Link]("three");

[Link](list);

sort()

The Collections sort() method can sort a Java [Link] is an example of sorting a
Java List using Collections sort() method:

List>String< list = new ArrayList<String>();

[Link]("one");
[Link]("two");
[Link]("three");
[Link]("four");

[Link](list);

After running this code the order of the elements in the List will be four, one, three, four, as
the String elements will be sorted alphabetically.

min()

The Collections min() method can find the minimum element in a List according to the
natural ordering of the elements (see my Java List sorting tutorial). Here is an example
of finding the minimum element in a Java List using Collections min() method:

List source = new ArrayList();


[Link]("1");
[Link]("2");
[Link]("3");

String min = (String) [Link](source);

After running the code above, the min variable will contain the String value 1 .
max()

The Collections max() method can find the maximum element in a List according to the
natural order of the elements. Here is an example of finding the maximum element in a
Java List:

List source = new ArrayList();


[Link]("1");
[Link]("2");
[Link]("3");

String max = (String) [Link](source);

After running the code above, the max variable will contain the String value 3 .

replaceAll()

The Java Collections replaceAll() method can replace all occurrences of one
element with another element. You pass the element to replace and the element
to replace it with as parameters to the replaceAll() method.
The Collections replaceAll() method returns true if any elements were replaced,
and false if not. Here is an example of replacing all occurrences of one element
with another in a Java List:

List source = new ArrayList();


[Link]("A");
[Link]("B");
[Link]("A");

boolean replacedAny = [Link](source, "A", "C");

After executing this example, the source List will contain the elements C, B and C.
The replacedAny variable will contain the value true because at least one element
was replaced in the List.

The Collections replaceAll() method uses the equals() method of each element
to determine if the element is equal to the element to replace or not. I have a
written a few more details about how the equals() method works in my section
about the Java equals() method.
unmodifiableSet()

The unmodifiableSet() method in the Java Collections class can create an


immutable (unmodifiable) Set from a normal Java Set . Here is a Java example
of creating an immutable Set from a normal Set:

Set normalSet = new HashSet();

Set immutableSet = [Link](normalSet);

What is the difference between Collection and Collections ?

"Collection is an "interface" which can be used to represent a group of objects as a

single entity. Whereas "Collections is an utility class" present in [Link] package to

define several utility methods for Collection objects.

Collection--------------------interface

Collections------------------class
Collection interface:

The Java Collection interface ([Link]) is one of the root interfaces of the Java Collection API.
Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often
treat these subtypes uniformly as a Collection.

If we want to represent a group of individual objects as a single entity then we should go for Collection
interface. This interface defines the most common general methods which can be applicable for any
Collection object.
The following is the list of methods present in Collection interface.

1. boolean add(Object o);

2. boolean addAll(Collection c);

3. boolean remove(Object o);

4. boolean removeAll(Object o);

5. boolean retainAll(Collection c); To remove all objects except those present in c.

6. Void clear();

7. boolean contains(Object o);

8. boolean containsAll(Collection c);

9. boolean isEmpty();

10. Int size();

11. Object[] toArray();

Create a Collection

As just mentioned above, you do not create a Collection instance directly, but an instance of
one of the subtypes of Collection. Here is an example of creating a List which is a subtype
of Collection:

Collection collection = new ArrayList();

The above example works for every subtype of Collection.

Collection Subtypes

The following interfaces (collection types) extends the Java Collection interface:

 List
 Set
 SortedSet
 NavigableSet
 Queue
 Deque
Java does not come with a usable implementation of the Collection interface, so you will have
to use one of the listed subtypes. The Collection interface just defines a set of methods
(behaviour) that each of these Collection subtypes share. This makes it possible ignore what
specific type of Collection you are using, and just treat it as a Collection. This is standard
inheritance, so there is nothing magical about, but it can still be a nice feature from time to
time. Later sections in this text will describe the most used of these common operations.

Here is a method that operates on a Collection:

public class MyCollectionUtil{

public static void doSomething(Collection collection) {

Iterator iterator = [Link]();


while([Link]()){
Object object = [Link]();

//do something to object here...


}
}
}

And here are a few ways to call this method with different Collection subtypes:

Set set = new HashSet();


List list = new ArrayList();

[Link](set);
[Link](list);

Add Element to Collection

Regardless of what Collection subtype you are using there are a few standard methods to add
elements to a Collection. Adding an element to a Collection is done via the add() method. Here
is an example of adding an element to a Java Collection:

String anElement = "an element";


Collection collection = new HashSet();

boolean didCollectionChange = [Link](anElement);


The add() method adds the given element to the collection, and returns true if
the Collection changed as a result of calling the add() method. A Set for instance may not have
changed. If the Set already contained that element, it is not added again. On the other hand, if
you called add() on a List and the List already contained that element, the element would then
exist twice in the List.

Remove Element From Collection

The remove() method removes the given element from the Collection and returns true if the
removed element was present in the Collection, and was removed. If the element was not
present, the remove() method returns false. Here is an example of removing an element from a
Java Collection:

boolean wasElementRemoved = [Link]("an element");

Add Collection of Objects to Collection

You can also add a collection of objects to a Java Collection using the addAll(). Here is an
example of adding a collection of objects to a Java Collection:

Set aSet = ... // get Set with elements from somewhere

Collection collection = new HashSet();

[Link](aSet); //returns boolean too, but ignored here

The Java Collection addAll() adds all elements found in the Collection passed as parameter to
the method. The Collection object itself is not added. Only its elements. If you had
called add() with the Collection as parameter instead, the Collection object itself would have
been added, not its elements.

Exactly how the addAll() method behaves depends on the Collection subtype. Some Collection
subtypes allows the same element to be added more than once, and others don't.

Remove Collection of Elements From Collection

The Java Collection removeAll() removes all elements found the Collection passed as parameter
to the method. If the Collection parameter contains any elements not found the target
collection, these are just ignored. Here is an example of removing a collection of elements from
a Java Collection:

Collection objects = //... get a collection of objects from somewhere.

[Link](objects);

Retain All Elements From a Collection in Another Collection

The Java Collection retainAll() does the opposite of removeAll(). Instead of removing all the
elements found in the parameter Collection, it keeps all these elements, and removes all other
elements. Keep in mind, that only if the elements were already contained in the target
collection, are they retained. Any new elements found in the parameter Collection which are
not in the target collection, are not automatically added. They are just ignored. Here is an
example of retaining all elements from one Colletion in another Java Collection:

Collection colA = new ArrayList();


Collection colB = new ArrayList();

[Link]("A");
[Link]("B");
[Link]("C");

[Link]("1");
[Link]("2");
[Link]("3");

Collection target = new HashSet();

[Link](colA); //target now contains [A,B,C]


[Link](colB); //target now contains [A,B,C,1,2,3]

[Link](colB); //target now contains [1,2,3]

Checking if a Collection Contains a Certain Element

The Collection interface has two methods to check if a Collection contains one or more certain
elements. These are the contains() and containsAll() methods. They are illustrated here:
Collection collection = new HashSet();
boolean containsElement = [Link]("an element");

Collection elements = new HashSet();


boolean containsAll = [Link](elements);

contains() returns true if the collection contains the element, and false if not.

containsAll() returns true if the collection contains all the elements in the parameter collection,
and false if not.

Collection Size

You can check the size of a collection using the size() method. By "size" is meant the number of
elements in the collection. Here is an example:

int numberOfElements = [Link]();

Iterate a Collection

You can iterate all elements of a collection. This is done by obtaining an Java Iterator from the
collection, and iterate through that. Here is how it looks:

Collection collection = new HashSet();


//... add elements to the collection

Iterator iterator = [Link]();


while([Link]()){
Object object = [Link]();
[Link](object);
}

You can also iterate a Java Collection using the Java for-each loop :

Collection collection = new HashSet();


[Link]("A");
[Link]("B");
[Link]("C");

for(Object object : collection) {


[Link](object);
}

List interface:
It is the child interface of Collection.

 If we want to represent a group of individual objects as a single entity where duplicates are allow and
insertion order is preserved. Then we should go for List.

 We can differentiate duplicate objects and we can maintain insertion order by means of index hence
"index play very important role in List".

List interface defines the following specific methods.

1. boolean add(int index,Object o);

2. boolean addAll(int index,Collectio c);

3. Object get(int index);

4. Object remove(int index);

5. Object set(int index,Object new);//to replace

6. Int indexOf(Object o); Returns index of first occurrence of "o".

7. Int lastIndexOf(Object o);

8. ListIterator listIterator();
ArrayList:
1. The underlying data structure is resizable array (or) growable array.

2. Duplicate objects are allowed.

3. Insertion order preserved.

4. Heterogeneous objects are allowed.(except TreeSet , TreeMap every where heterogenious objects are
allowed)

5. Null insertion is possible.

Constructor :

1) ArrayList a = new ArrayList();


Creates an empty ArrayList object with default initial capacity "10" if ArrayList reaches its max
capacity then a new ArrayList object will be created with New capacity=(current capacity*3/2)+1

2) ArrayList a=new ArrayList(int initialcapacity);


Creates an empty ArrayList object with the specified initial capacity.

3) ArrayList a=new ArrayList(collection c);


Creates an equivalent ArrayList object for the given Collection that is this constructor meant for
inter conversation between collection objects. That is to dance between collection objects.
Suppose you have a List or Set and you want to convert it into an ArrayList.
You can use this constructor:
List<String> list = [Link]("Apple", "Banana", "Cherry");
ArrayList<String> arrayList = new ArrayList<>(list);

 Usually we can use collection to hold and transfer objects from one tier to another tier. To provide support for
this requirement every Collection class already implements Serializable and Cloneable interfaces.
 ArrayList and Vector classes implements RandomAccess interface so that any random element we can access
with the same speed. Hence ArrayList is the best choice of "retrival operation".
 RandomAccess interface present in util package and doesn't contain any methods. It is a marker interface.
LIST VS ARRAYLIST :

Getting synchronized version of ArrayList object:


 Collections class defines the following method to return synchronized version of List.

Public static List synchronizedList(list l);

 Example:
 Similarly we can get synchronized version of Set and Map objects by using the following methods. 1)
public static Set synchronizedSet(Set s); 2) public static Map synchronizedMap(Map m);

 ArrayList is the best choice if our frequent operation is retrieval.

 ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the middle because it
requires several internal shift operations.

LinkedList :
1. The underlying data structure is double LinkedList

2. If our frequent operation is insertion (or) deletion in the middle then LinkedList is the best choice.

3. If our frequent operation is retrieval operation then LinkedList is worst choice.

4. Duplicate objects are allowed.

5. Insertion order is preserved.

6. Heterogeneous objects are allowed.

7. Null insertion is possible.

8. Implements Serializable and Cloneable interfaces but not RandomAccess.

Usually we can use LinkedList to implement Stacks and Queues. To provide support for this requirement
LinkedList class defines the following 6 specific methods.

1. void addFirst(Object o);

2. void addLast(Object o);

3. Object getFirst();

4. Object getLast();

5. Object removeFirst();
6. Object removeLast(); We can apply these methods only on LinkedList object.

Constructors:

1. LinkedList l=new LinkedList(); Creates an empty LinkedList object.

2. LinkedList l=new LinkedList(Collection c); To create an equivalent LinkedList object for the given
collection.

Vector:
1. The underlying data structure is resizable array (or) growable array.

2. Duplicate objects are allowed.

3. Insertion order is preserved.

4. Heterogeneous objects are allowed.

5. Null insertion is possible.

6. Implements Serializable, Cloneable and RandomAccess interfaces. Every method present in Vector is
synchronized and hence Vector is Thread safe.

Vector specific methods:


To add objects:

1. add(Object o);-----Collection

2. add(int index,Object o);-----List

3. addElement(Object o);-----

Vector To remove elements:

1. remove(Object o);--------Collection

2. remove(int index);--------------List 3

. removeElement(Object o);----Vector

4. removeElementAt(int index);-----Vector

5. removeAllElements();-----Vector

6. clear();-------

Collection To get objects:


1. Object get(int index);---------------List

2. Object elementAt(int index);-----Vector

3. Object firstElement();--------------Vector

4. Object lastElement();---------------

Vector Other methods:

1. Int size();//How many objects are added

2. Int capacity();//Total capacity

3. Enumeration elements();

Constructors:

Vector v=new Vector();

Creates an empty Vector object with default initial capacity 10. o Once Vector reaches its maximum
capacity then a new Vector object will be created with double capacity. That is
"newcapacity=currentcapacity*2".

2. Vector v=new Vector(int initialcapacity);

3. Vector v=new Vector(int initialcapacity, int incrementalcapacity);

4. Vector v=new Vector(Collection c);

Stack:
1. It is the child class of Vector.

2. Whenever last in first out(LIFO) order required then we should go for Stack. Constructor: It contains
only one constructor.

Stack s= new Stack();

Methods:

Object push(Object o);

To insert an object into the stack.

2. Object pop();

To remove and return top of the stack.

3. Object peek();

To return top of the stack without removal.


4. boolean empty();

Returns true if Stack is empty.

5. Int search(Object o);

Returns offset if the element is available otherwise returns "-1"

Difference Between ArrayList and LinkedList in Java

When to Use Which?

 Use ArrayList when you need fast random access (get(index)) and less memory overhead.
 Use LinkedList when you have frequent insertions and deletions (especially in the middle)
and don't need fast random access

The 3 cursors of java:


If we want to get objects one by one from the collection then we should go for cursor.

There are 3 types of cursors available in java. They are:

1. Enumeration

2. Iterator

3. ListIterator

Enumeration:
1. We can use Enumeration to get objects one by one from the legacy collection objects.

2. We can create Enumeration object by using elements() method.

public Enumeration elements();

Enumeration e=[Link]();

using Vector Object Enumeration interface defines the following two methods

1. public boolean hasMoreElements();

2. public Object nextElement();

Limitations of Enumeration:

1. We can apply Enumeration concept only for legacy classes and it is not a universal cursor.

2. By using Enumeration we can get only read access and we can't perform remove operations.

3. To overcome these limitations sun people introduced Iterator concept in 1.2v.

Enumeration can only be used with legacy classes such as:

 Vector
 Hashtable
 Properties
 Stack
Enumeration is one of the oldest cursor interfaces in Java, introduced in JDK 1.0. It is
used to iterate over elements of legacy collection classes like Vector and Hashtable.
However, it has several limitations, which led to the introduction of more advanced
iterators like Iterator and ListIterator

Iterator:
1. We can use Iterator to get objects one by one from any collection object.

2. We can apply Iterator concept for any collection object and it is a universal cursor.

3. While iterating the objects by Iterator we can perform both read and remove operations. We can get
Iterator object by using iterator() method of Collection interface.

public Iterator iterator();

Iterator itr=[Link]();

Iterator interface defines the following 3 methods.

1. public boolean hasNext();

2. public object next();

3. public void remove();

Limitations of Iterator :

1. Both enumeration and Iterator are single direction cursors only. That is we can always move only
forward direction and we can't move to the backward direction.

2. While iterating by Iterator we can perform only read and remove operations and we can't perform
replacement and addition of new objects.

3. To overcome these limitations sun people introduced listIterator concept

ListIterator:
1. ListIterator is the child interface of Iterator.

2. By using listIterator we can move either to the forward direction (or) to the backward direction that is
it is a bi-directional cursor.

3. While iterating by listIterator we can perform replacement and addition of new objects in addition to
read and remove operations By using listIterator method we can create listIterator object.

public ListIterator listIterator();


ListIterator itr=[Link](); (l is any List object)

ListIterator interface defines the following 9 methods.

1. public boolean hasNext();

2. public Object next(); forward

3. public int nextIndex();

4. public boolean hasPrevious();

5. public Object previous(); backward

6. public int previousIndex();

7. public void remove();

8. public void set(Object new);

9. public void add(Object new);

The most powerful cursor is listIterator but its limitation is it is applicable only for "List objects".
Set interface:
1. It is the child interface of Collection.

2. If we want to represent a group of individual objects as a single entity where duplicates are not allow
and insertion order is not preserved then we should go for Set interface.

Set interface does not contain any new method we have to use only Collection interface methods.

HashSet :

1. The underlying data structure is Hashtable.

2. Insertion order is not preserved and it is based on hash code of the objects. 3. Duplicate objects are
not allowed.

4. If we are trying to insert duplicate objects we won't get compile time error and runtime error add()
method simply returns false.

5. Heterogeneous objects are allowed.

6. Null insertion is possible.(only once)

7. Implements Serializable and Cloneable interfaces but not RandomAccess. 8. HashSet is best suitable, if
our frequent operation is "Search".
Constructors:

Java provides multiple constructors for HashSet, each serving different purposes:

1. HashSet h = new HashSet();


o Creates an empty HashSet with:
 Default initial capacity of 16
 Default load factor (fill ratio) of 0.75
o Meaning: When the number of elements in the HashSet exceeds 16 * 0.75 = 12, the
capacity increases (doubles).

2. HashSet h = new HashSet(int initialCapacity);


o Creates an empty HashSet with a user-defined initial capacity but keeps the default load
factor (0.75).
o Example:

java
CopyEdit
HashSet<Integer> set = new HashSet<>(32);

o Meaning: The HashSet will resize after inserting 32 * 0.75 = 24 elements.

3. HashSet h = new HashSet(int initialCapacity, float fillRatio);


o Creates a HashSet with a custom initial capacity and load factor.
o Example:

java
CopyEdit
HashSet<Integer> set = new HashSet<>(32, 0.5f);

o Meaning: Resizing happens when 32 * 0.5 = 16 elements are inserted.

4. HashSet h = new HashSet(Collection c);


o Creates a HashSet containing all elements from the specified Collection.
o Example:

java
CopyEdit
ArrayList<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
HashSet<String> set = new HashSet<>(list);

o Meaning: The HashSet is initialized with the elements of list.


What is Load Factor (Fill Ratio)?

 The load factor (fill ratio) determines when the HashSet increases its capacity.
 Formula for resizing:

New Capacity = Old Capacity * 2

when the number of elements exceeds (capacity * load factor).

Example:
java
CopyEdit
HashSet<Integer> set = new HashSet<>(8, 0.5f);

 Initial Capacity = 8
 Load Factor = 0.5
 Resize happens after 8 * 0.5 = 4 elements are inserted.
 After resizing, the new capacity becomes 16.

Why is Load Factor Important?

 A lower load factor (e.g., 0.5) reduces collisions but increases memory usage.
 A higher load factor (e.g., 0.9) reduces memory usage but may cause more collisions, affecting
performance.

LinkedHashSet :
1. It is the child class of HashSet.

2. LinkedHashSet is exactly same as HashSet except the following differences.


Note: LinkedHashSet and LinkedHashMap commonly used for implementing "cache applications"
where insertion order must be preserved and duplicates are not allowed.

TreeSet:
TreeSet is a part of Java's [Link] package and implements the SortedSet interface. It is a
sorted collection that stores unique elements in a sorted order.

Unlike HashSet, which uses hashing, TreeSet is implemented using a self-balancing Red-
Black tree. This ensures that all operations like insertion, deletion, and lookup run in O(log n)
time.

1. The underlying data structure is balanced tree.

2. Duplicate objects are not allowed.

3. Insertion order is not preserved and it is based on some sorting order of objects.

4. Heterogeneous objects are not allowed if we are trying to insert heterogeneous objects then we will
get ClassCastException.

5. Null insertion is not possible(only .

TreeSet Constructors
1. TreeSet t = new TreeSet();

 Creates an empty TreeSet that maintains elements in natural sorting order (ascending
order for numbers, lexicographic order for strings).
 Elements must be comparable, otherwise, it will throw ClassCastException.

Example:

import [Link];

public class TreeSetExample {


public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
[Link](50);
[Link](20);
[Link](10);
[Link](40);

[Link](set); // Output: [10, 20, 40, 50] (Sorted Order)


}
}

Explanation:

 The numbers are automatically sorted in ascending order.


 The default sorting follows the Comparable interface (Integer implements Comparable).

2. TreeSet t = new TreeSet(Comparator c);

 Creates an empty TreeSet but allows custom sorting order using a Comparator.
 Useful when you need descending order sorting or custom sorting logic.

Example: Sorting in Descending Order

java
CopyEdit
import [Link].*;

public class TreeSetWithComparator {


public static void main(String[] args) {
// Custom Comparator for descending order
TreeSet<Integer> set = new TreeSet<>([Link]());

[Link](50);
[Link](20);
[Link](10);
[Link](40);

[Link](set); // Output: [50, 40, 20, 10] (Descending Order)


}
}

Explanation:

 [Link]() is used for descending sorting.


 Elements are inserted according to the custom comparator logic.
3. TreeSet t = new TreeSet(SortedSet s);

 Creates a TreeSet from an existing SortedSet.


 The new TreeSet maintains the same sorting order as the given SortedSet.

Example:

java
CopyEdit
import [Link].*;

public class TreeSetFromSortedSet {


public static void main(String[] args) {
SortedSet<Integer> sortedSet = new TreeSet<>();
[Link](100);
[Link](50);
[Link](150);

// Creating TreeSet from SortedSet


TreeSet<Integer> treeSet = new TreeSet<>(sortedSet);

[Link](treeSet); // Output: [50, 100, 150]


}
}

Explanation:

 SortedSet maintains elements in sorted order.


 The TreeSet copies all elements while preserving the same sorting order.

4. TreeSet t = new TreeSet(Collection c);

 Creates a TreeSet and adds all elements from an existing Collection.


 The elements must be comparable; otherwise, ClassCastException will occur.
 Useful when you want to remove duplicates and sort elements from a collection.

Example:

java
CopyEdit
import [Link].*;
public class TreeSetFromCollection {
public static void main(String[] args) {
List<Integer> list = [Link](30, 10, 20, 10, 50, 20);

// Creating TreeSet from Collection (List)


TreeSet<Integer> treeSet = new TreeSet<>(list);

[Link](treeSet); // Output: [10, 20, 30, 50] (Sorted + Duplicates Removed)


}
}

Explanation:

 The TreeSet automatically sorts the elements.


 Duplicates (10 and 20) are removed.

Key Takeaways
Constructor Description

TreeSet() Creates an empty TreeSet with natural sorting order.

TreeSet(Comparator c) Creates a TreeSet with custom sorting order (e.g., descending order).

TreeSet(SortedSet s) Creates a TreeSet from an existing SortedSet, keeping the same order.

TreeSet(Collection c) Creates a TreeSet from a Collection (removes duplicates and sorts).

Null acceptance:

 For the empty TreeSet as the 1st element "null" insertion is possible but after inserting that null if we
are trying to insert any other we will get NullPointerException.

 For the non empty TreeSet if we are trying to insert null then we will get NullPointerException

Comparable interface:

Comparable interface present in [Link] package and contains only one method compareTo()
method.

public int compareTo(Object obj);


Example: [Link](obj2);

Java Comparable interface is used to order the objects of the user-defined class. This interface
is found in [Link] 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.

If we are depending on default natural sorting order then internally JVM will use
compareTo() method to arrange objects in sorting order.
 If we are not satisfying with default natural sorting order (or) if default natural
sorting order is not available then we can define our own customized sorting by
Comparator object.
 Comparable meant for default natural sorting order.
 Comparator meant for customized sorting order.

Comparator interface:
Comparator interface present in [Link] package this interface defines the following 2 methods.

1) public int compare(Object obj1,Object Obj2);


2) public boolean equals(Object obj);
 Whenever we are implementing Comparator interface we have to provide implementation
only for compare() method.
 Implementing equals() method is optional because it is already available from Object class
through inheritance.

public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub
TreeSet t=new TreeSet(new
MyComparator()); //---

[Link](10);
[Link](0);
[Link](15);
[Link](5);
[Link](20);
[Link](t);

}
 At line "1" if we are not passing Comparator object then JVM will always calls compareTo()
method which is meant for default natural sorting order(ascending order)hence in this case the
output is [0, 5, 10, 15, 20].
 At line "1" if we are passing Comparator object then JVM calls compare() method of
MyComparator class which is meant for customized sorting order(descending order) hence in
this case the output is [20, 15, 10, 5, 0].

Requirement: Write a program to insert String objects into the TreeSet where the sorting order
is reverse of alphabetical order.

Comparable vs Comparator:
 For predefined Comparable classes default natural sorting order is already available if we are
not satisfied with default natural sorting order then we can define our own customized sorting
order by Comparator.
 For predefined non Comparable classes [like StringBuffer] default natural sorting order is not
available we can define our own sorting order by using Comparator object.
 For our own classes [like Customer, Student, and Employee] we can define default natural
sorting order by using Comparable interface. The person who is using our class, if he is not
satisfied with default natural sorting order then he can define his own sorting order by using
Comparator object
1. ArrayList Questions
Q1. Find the frequency of an element in an ArrayList.

Write a program to count how many times a specific element appears in


an ArrayList.

java
Copy
import [Link];
import [Link];

public class FrequencyExample {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](2);
[Link](4);
[Link](2);

int element = 2;
int frequency = [Link](list, element);
[Link]("Frequency of " + element + ": " + frequency);
}
}
Q2. Remove duplicates from an ArrayList.

Write a program to remove duplicate elements from an ArrayList.

java
Copy
import [Link];
import [Link];

public class RemoveDuplicates {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](2);
[Link](4);

HashSet<Integer> set = new HashSet<>(list); // Convert to Set to remove duplicates


[Link]();
[Link](set); // Convert back to ArrayList

[Link]("List after removing duplicates: " + list);


}
}

2. LinkedList Questions
Q3. Reverse a LinkedList.

Write a program to reverse a LinkedList.

java
Copy
import [Link];
import [Link];

public class ReverseLinkedList {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](4);

[Link](list); // Reverse the LinkedList


[Link]("Reversed LinkedList: " + list);
}
}
Q4. Find the middle element of a LinkedList.

Write a program to find the middle element of a LinkedList.

java
Copy
import [Link];

public class MiddleElement {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);

int middleIndex = [Link]() / 2;


int middleElement = [Link](middleIndex);
[Link]("Middle Element: " + middleElement);
}
}

3. Set Questions
Q5. Check if two arrays have the same elements (ignoring duplicates).

Write a program to check if two arrays contain the same elements, ignoring
duplicates, using a Set.

java
Copy
import [Link];
import [Link];
import [Link];

public class SameElements {


public static void main(String[] args) {
Integer[] array1 = {1, 2, 3, 4, 2};
Integer[] array2 = {4, 3, 2, 1};

Set<Integer> set1 = new HashSet<>([Link](array1));


Set<Integer> set2 = new HashSet<>([Link](array2));

[Link]("Do the arrays have the same elements? " + [Link](set2));


}
}
Q6. Find the union and intersection of two sets.

Write a program to find the union and intersection of two sets.

java
Copy
import [Link];
import [Link];

public class UnionIntersection {


public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
[Link](1);
[Link](2);
[Link](3);

Set<Integer> set2 = new HashSet<>();


[Link](3);
[Link](4);
[Link](5);

// Union
Set<Integer> union = new HashSet<>(set1);
[Link](set2);
[Link]("Union: " + union);

// Intersection
Set<Integer> intersection = new HashSet<>(set1);
[Link](set2);
[Link]("Intersection: " + intersection);
}
}

4. Mixed Questions
Q7. Convert an ArrayList to a LinkedList and vice versa.

Write a program to convert an ArrayList to a LinkedList and a LinkedList to


an ArrayList.

java
Copy
import [Link];
import [Link];
import [Link];

public class ConvertLists {


public static void main(String[] args) {
// ArrayList to LinkedList
ArrayList<String> arrayList = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");

LinkedList<String> linkedList = new LinkedList<>(arrayList);


[Link]("ArrayList to LinkedList: " + linkedList);

// LinkedList to ArrayList
List<String> newArrayList = new ArrayList<>(linkedList);
[Link]("LinkedList to ArrayList: " + newArrayList);
}
}

Q8. Find common elements between two ArrayLists.

Write a program to find common elements between two ArrayLists.

java
Copy
import [Link];
import [Link];

public class CommonElements {


public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);

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


[Link](3);
[Link](4);
[Link](2);

HashSet<Integer> set = new HashSet<>(list1);


[Link](list2); // Retain only common elements
[Link]("Common Elements: " + set);
}
}

Key Takeaways
 ArrayList: Good for random access and iteration but slower for
insertions/deletions in the middle.

 LinkedList: Good for frequent insertions/deletions but slower for


random access.
 Set: Used to store unique elements. Common implementations
are HashSet, LinkedHashSet, and TreeSet.

Q9. Sort an ArrayList in ascending and descending order.

Write a program to sort an ArrayList in ascending and descending order.

java

Copy
import [Link];
import [Link];

public class SortArrayList {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](5);
[Link](2);
[Link](8);
[Link](1);

// Ascending order
[Link](list);
[Link]("Ascending Order: " + list);

// Descending order
[Link](list, [Link]());
[Link]("Descending Order: " + list);
}
}

Q10. Merge two ArrayLists into one.

Write a program to merge two ArrayLists into a single ArrayList.

java

Copy
import [Link];

public class MergeArrayLists {


public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);

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


[Link](4);
[Link](5);
[Link](6);

[Link](list2); // Merge list2 into list1


[Link]("Merged ArrayList: " + list1);
}
}

Q11. Find the second largest element in an ArrayList.

Write a program to find the second largest element in an ArrayList.

java

Copy
import [Link];
import [Link];

public class SecondLargest {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](20);
[Link](5);
[Link](30);

[Link](list); // Sort the list


int secondLargest = [Link]([Link]() - 2); // Get the second last element
[Link]("Second Largest Element: " + secondLargest);
}
}

2. LinkedList Questions
Q12. Remove the first and last element from a LinkedList.

Write a program to remove the first and last element from a LinkedList.

java

Copy
import [Link];

public class RemoveFirstLast {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link](); // Remove first element
[Link](); // Remove last element

[Link]("LinkedList after removal: " + list);


}
}

Q13. Check if a LinkedList is a palindrome.

Write a program to check if a LinkedList is a palindrome.

java

Copy
import [Link];
import [Link];

public class PalindromeCheck {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](2);
[Link](1);

LinkedList<Integer> reversedList = new LinkedList<>(list);


[Link](reversedList); // Reverse the list

boolean isPalindrome = [Link](reversedList); // Compare original and reversed list


[Link]("Is the LinkedList a palindrome? " + isPalindrome);
}
}

Q14. Swap two elements in a LinkedList.

Write a program to swap two elements in a LinkedList.

java

Copy
import [Link];
import [Link];

public class SwapElements {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link](list, 1, 3); // Swap elements at index 1 and 3
[Link]("LinkedList after swapping: " + list);
}
}

3. Set Questions
Q15. Find the difference between two sets.

Write a program to find the difference between two sets.

java

Copy
import [Link];
import [Link];

public class SetDifference {


public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
[Link](1);
[Link](2);
[Link](3);

Set<Integer> set2 = new HashSet<>();


[Link](3);
[Link](4);
[Link](5);

Set<Integer> difference = new HashSet<>(set1);


[Link](set2); // Remove elements of set2 from set1
[Link]("Difference (set1 - set2): " + difference);
}
}

Q16. Check if a Set is a subset of another Set.

Write a program to check if a Set is a subset of another Set.

java

Copy
import [Link];
import [Link];

public class SubsetCheck {


public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
[Link](1);
[Link](2);
[Link](3);

Set<Integer> set2 = new HashSet<>();


[Link](2);
[Link](3);

boolean isSubset = [Link](set2); // Check if set2 is a subset of set1


[Link]("Is set2 a subset of set1? " + isSubset);
}
}

Q17. Convert a Set to an ArrayList.

Write a program to convert a Set to an ArrayList.

java

Copy
import [Link];
import [Link];
import [Link];

public class SetToArrayList {


public static void main(String[] args) {
Set<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

ArrayList<String> list = new ArrayList<>(set); // Convert Set to ArrayList


[Link]("ArrayList from Set: " + list);
}
}

4. Mixed Questions
Q18. Find the intersection of an ArrayList and a LinkedList.

Write a program to find the intersection of an ArrayList and a LinkedList.

java

Copy
import [Link];
import [Link];
import [Link];
import [Link];

public class IntersectionMixed {


public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);

LinkedList<Integer> linkedList = new LinkedList<>();


[Link](3);
[Link](4);
[Link](2);

Set<Integer> set = new HashSet<>(arrayList);


[Link](linkedList); // Retain only common elements
[Link]("Intersection: " + set);
}
}

Q19. Remove all elements from a LinkedList that are present in a Set.

Write a program to remove all elements from a LinkedList that are present in a Set.

java

Copy
import [Link];
import [Link];
import [Link];

public class RemoveElements {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Date");

Set<String> set = new HashSet<>();


[Link]("Banana");
[Link]("Date");

[Link](set); // Remove elements present in the set


[Link]("LinkedList after removal: " + list);
}
}

Q20. Find the union of an ArrayList and a LinkedList.

Write a program to find the union of an ArrayList and a LinkedList.

java

Copy
import [Link];
import [Link];
import [Link];
import [Link];

public class UnionMixed {


public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);

LinkedList<Integer> linkedList = new LinkedList<>();


[Link](3);
[Link](4);
[Link](5);

Set<Integer> union = new HashSet<>(arrayList);


[Link](linkedList); // Add all elements from both collections
[Link]("Union: " + union);
}
}

Key Takeaways
 ArrayList: Best for frequent read operations and random access.

 LinkedList: Best for frequent insertions/deletions, especially at the beginning or


end.

 Set: Ensures uniqueness and is useful for operations like union, intersection, and
difference.

These additional questions will help you practice and master the Java Collection
Framework. Keep coding! 🚀

MAP :
1. If we want to represent a group of objects as "key-value" pair then we should go for Map interface.

2. Both key and value are objects only.

3. Duplicate keys are not allowed but values can be duplicated

4. Each key-value pair is called "one entry".


 Map interface is not child interface of Collection and hence we can't apply Collection interface
methods here.

 Map interface defines the following specific methods.

 Object put(Object key,Object value); To add an entry to the Map, if key is already available then
the old value replaced with new value and old value will be returned.
 void putAll(Map m);
 Object get(Object key);
 Object remove(Object key);
 It removes the entry associated with specified key and returns the corresponding
 value.
 boolean containsKey(Object key);
 boolean containsValue(Object value);
 boolean isEmpty();
 Int size();
 void clear();
 Set keySet();
 The set of keys we are getting.
 Collection values();
 The set of values we are getting.
 Set entrySet();
 The set of entryset we are getting

Entry interface:

Each key-value pair is called one entry. Hence Map is considered as a group of entry Objects, without
existing Map object there is no chance of existing entry object hence interface entry is define inside Map
interface(inner interface).

HashMap:
1. The underlying data structure is Hashtable.

2. Duplicate keys are not allowed but values can be duplicated.

3. Insertion order is not preserved and it is based on hash code of the keys.

4. Heterogeneous objects are allowed for both key and value.

5. Null is allowed for keys(only once) and for values(any number of times).

6. It is best suitable for Search operations.

Constructors:

1. HashMap m=new HashMap();


2. Creates an empty HashMap object with default initial capacity 16 and
default fill ratio "0.75".
3. 2. HashMap m=new HashMap(int initialcapacity);
4. 3. HashMap m =new HashMap(int initialcapacity, float fillratio);
5. 4. HashMap m=new HashMap(Map m);
How to Iterate Over a HashMap in Java

There are multiple ways to iterate over a HashMap in Java. Below are the different approaches:

1. Using forEach with Lambda (Java 8+) 🔥 (Recommended)


java
CopyEdit
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");

// Using forEach with lambda


[Link]((key, value) -> [Link](key + " -> " + value));
}
}

✅ Best for modern Java (concise and readable)

2. Using entrySet() with Enhanced For-Loop


java
CopyEdit
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}

✅ Recommended for traditional iteration (efficient and clean)

3. Using keySet() to Iterate Over Keys


java
CopyEdit
for (Integer key : [Link]()) {
[Link](key + " -> " + [Link](key));
}

⚠ Less efficient because [Link](key) is called repeatedly.

4. Using values() to Iterate Over Values


java
CopyEdit
for (String value : [Link]()) {
[Link](value);
}

✅ Useful when you only need values (No access to keys).

5. Using Iterator with entrySet() (Best for Removing Elements)


java
CopyEdit
import [Link];
import [Link];

Iterator<[Link]<Integer, String>> iterator = [Link]().iterator();


while ([Link]()) {
[Link]<Integer, String> entry = [Link]();
[Link]([Link]() + " -> " + [Link]());
}

✅ Best when you need to remove elements safely using [Link]().

6. Using Stream API (Java 8+)


java
CopyEdit
[Link]().stream()
.forEach(entry -> [Link]([Link]() + " -> " +
[Link]()));

✅ Useful for functional programming and parallel execution.

HashMap Internal Implementation :


Structure of HashMap
1. Array of Buckets:
a. The HashMap uses an array to store its entries, where each entry is represented as a
linked list (or tree in case of high collision) to handle multiple entries that hash to the
same index. Each index in the array is referred to as a bucket.
b. The array is initialized with a default capacity (usually 16) and can grow dynamically as
more entries are added.

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Node Class :

The Node class has the following fields:


 hash: Refers to the hashCode of the key.
 key: Refers to the key of the key-value pair.
 value: Refers to the value associated with the key.
 next: Acts as a reference to the next node.

 The capacity is the number of buckets in the hash table,


and the initial capacity is simply the capacity at the
time the hash table is created.
 The load factor is a measure of how full the hash table
is allowed to get before its capacity is automatically
increased.

Hash Function
During the insertion (put) of a key-value pair, the HashMap first
calculates the hash code of the key. The hash function then
computes an integer for the key. Classes can use
the hashCode method of the Object class or override this method
and provide their own implementation. (Read about the hash
code contract here). The hash code is then XORed (eXclusive
OR) with its upper 16 bits (h >>> 16) to achieve a more uniform
distribution.
XOR is a bitwise operation that compares two bits, resulting in 1
if the bits are different and 0 if they are the same. In this
context, performing a bitwise XOR operation between the hash
code and its upper 16 bits (obtained using the unsigned right
shift >>> operator) helps to mix the bits, leading to a more
evenly distributed hash code.
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = [Link]()) ^ (h >>> 16);
}

Index Calculation
Once the hash code for a key is generated,
the HashMap calculates an index within the array of buckets to
determine where the key-value pair will be stored. This is done
using a bitwise AND operation, which is an efficient way to
calculate the modulo when the array length is a power of two.
int index = (n - 1) & hash;

 Put operation: A put operation adds data to a data structure or an entry to a


bucket in a hashmap.

Syntax of put operation:

String key = "my-key";

String value = "my-value";

[Link](key, value);

 Get operation:A get operation retrieves data from a data structure or an entry
from a bucket in a hashmap.
 Chaining/Linking: Each bucket in the array is a linked
list of nodes. If a key already exists at a particular index
and another key gets hashed to the same index, it gets
appended to the list.
 Treeify: If the number of nodes exceeds a certain
threshold, the linked list is converted into a tree (This
was introduced in Java 8).
Time Complexity
The basic operations of a HashMap, such as put, get, and remove,
generally offer constant time performance of O(1), assuming
that the keys are uniformly distributed. In cases where there is
poor key distribution and many collisions occur, these
operations might degrade to a linear time complexity of O(n).
Under treeification, where long chains of collisions are
converted into balanced trees, lookup operations can improve
to a more efficient logarithmic time complexity of O(log n).
TreeMap:
1. The underlying data structure is RED-BLACK Tree.

2. Duplicate keys are not allowed but values can be duplicated.

3. Insertion order is not preserved and all entries will be inserted according to some sorting order of
keys.

4. If we are depending on default natural sorting order keys should be homogeneous and Comparable
otherwise we will get ClassCastException.

5. If we are defining our own sorting order by Comparator then keys can be heterogeneous and non
Comparable.

6. There are no restrictions on values they can be heterogeneous and non Comparable.

7. For the empty TreeMap as first entry null key is allowed but after inserting that entry if we are trying
to insert any other entry we will get NullPointerException.

8. For the non empty TreeMap if we are trying to insert an entry with null key we will get
NullPointerException.

9. There are no restrictions for null values.

Constructors:

1. TreeMap t=new TreeMap(); For default natural sorting order.

2. TreeMap t=new TreeMap(Comparator c); For customized sorting order.

3. TreeMap t=new TreeMap(SortedMap m);

4. TreeMap t=new TreeMap(Map m);


Queue interface :
1. Queue is child interface of Collections.

2. If we want to represent a group of individual objects prior (happening before something else) to
processing then we should go for Queue interface.

3. Usually Queue follows first in first out(FIFO) order but based on our requirement we can implement
our own order also.

4. From 1.5v onwards LinkedList also implements Queue interface.

5. LinkedList based implementation of Queue always follows first in first out order.

Link : [Link]

Link : [Link]

Link : [Link]

Link : [Link]

Question: Word Frequency Counter

Write a Java program that takes a string as input and returns a Map<String,
Integer> where the key is each unique word in the string, and the value is the
frequency of that word in the string.
Requirements:
1. Ignore case sensitivity (e.g., "Hello" and "hello" should be treated as
the same word).

2. Remove punctuation from the string (e.g., "hello!" should be treated as


"hello").

3. Split the string into words based on spaces.

4. Return the map sorted by word frequency in descending order. If two


words have the same frequency, sort them alphabetically.

3. Sort a Map by Keys

Question: Write a program to sort a Map by its keys.

Answer:

java
Copy
import [Link].*;

public class SortMapByKey {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("apple", 10);
[Link]("banana", 5);
[Link]("cherry", 20);

TreeMap<String, Integer> sortedMap = new TreeMap<>(map);


[Link](sortedMap);
}
}
Sort a Map by Values

Question: Write a program to sort a Map by its values.

Answer:

java
Copy
import [Link].*;

public class SortMapByValue {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("apple", 10);
[Link]("banana", 5);
[Link]("cherry", 20);

List<[Link]<String, Integer>> list = new ArrayList<>([Link]());


[Link]([Link]());

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


for ([Link]<String, Integer> entry : list) {
[Link]([Link](), [Link]());
}

[Link](sortedMap);
}
}

You might also like