0% found this document useful (0 votes)
10 views52 pages

Unit IV-oop Java-Part II

The Java Set interface, part of the Collections framework, represents a collection of unique elements without preserving order. Key implementations include HashSet, LinkedHashSet, and TreeSet, each offering different functionalities and performance characteristics. The interface supports various operations such as union, intersection, and subset checks, while also providing methods for element manipulation and retrieval.
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)
10 views52 pages

Unit IV-oop Java-Part II

The Java Set interface, part of the Collections framework, represents a collection of unique elements without preserving order. Key implementations include HashSet, LinkedHashSet, and TreeSet, each offering different functionalities and performance characteristics. The interface supports various operations such as union, intersection, and subset checks, while also providing methods for element manipulation and retrieval.
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
You are on page 1/ 52

Java Set Interface

The Set interface of the Java Collections framework provides the features of the mathematical
set in Java. It extends the Collection interface.
Set(I): Set is the child interface of Collection interface. If we want to represent a
group of individual objects as single entity where duplicates are not allowed and
insertion order not preserved, then we go for Set.
• Unlike the List interface, sets cannot contain duplicate elements.

Classes that implement Set


Since Set is an interface, we cannot create objects from it. In order to use functionalities of
the Set interface, we can use these classes. These classes are defined in
the Collections framework and implement the Set interface.

• HashSet
• LinkedHashSet
• TreeSet

Interfaces that extend Set


The Set interface is also extended by these subinterfaces:
• SortedSet
• NavigableSet

Note: Set interface doesn’t contain any new method and we must use only Collection
interface methods.
In Java, we must import java.util Set package in order to use Set.

Methods of Set
The Set interface includes all the methods of the Collection interface. It's because Collection is
a super interface of Set.
Some of the commonly used methods of the Collection interface that's also available in
the Set interface are:
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified
set
• retainAll() - retains all the elements in the set that are also present in another specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified collection
• hashCode() - returns a hash code value (address of the element in the set)

Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union,
intersection, and subset.
• Union - to get the union of two sets x and y, we can use x.addAll(y)
• Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
• Subset - to check if x is a subset of y, we can use y.containsAll(x)

Java HashSet Class

The HashSet class of the Java Collections framework provides the functionalities of the hash
table data structure.
It implements the Set interface.

HashSet(C): HashSet is a class presents in java.util package which


extends(inherits) from AbstractSet class and implements from Set, Cloneable and
Serializable interfaces.

Properties:
 The underlying DS is Hash table.
 Duplicate objects are not allowed, Insertion order is not preserved and
it is based on hash code of objects.
 Heterogeneous elements are allowed and null insertion is possible (only once).
 If our frequent operation is search, then HashSet is the best choice.
Note: In HashSet duplicates are not allowed if we are trying to insert
duplicates then we won’t get any compile time or run time errors and add()
method simply returns false.
Ex: HashSet h=newHashSet();
SOP(h.add(“A”)); // true
SOP(h.add(“A”));//false

Implementing HashSet Class


import java.util.Set;
import java.util.HashSet;

class Main {

public static void main(String[] args) {


// Creating a Hash set using the HashSet class
HashSet<Integer> set1 = new HashSet<>();

// Add elements to the set1


set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);

// Creating another set using the HashSet class


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

// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);

// Union of two sets


set2.addAll(set1);
System.out.println("Union is: " + set2);
}
}
Run Code
Output
Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]

Declaration:
Public class HashSet<E> extends AbstractSet<E>implements Set<E>,
Cloneable, Serializable

Constructors:
(a) HashSet h= new HashSet();
Creates an empty HashSet object with default initial capacity 16 and
default fill ratio 0.75.
(b) HashSet h=new HashSet(int initial_capacity); Creates an empty
HashSet object with specified initial capacity and default fill ratio
0.75
(c) HashSet h=new HashSet (intinitial_capacity,float fill_ratio);
(d) HashSet h=new HashSet(Collectionc);
Creates an equivalent HashSet object for the given Collection. This
constructor meant for inter conversion between collection objects.

Fill Ratio (or) Load Factor: After filling how much ratio a new HashSet object
will be created, this ratio is called Fill Ratio. For example fill ratio 0.75 means after
filling 75% ratio a new HashSet object will be created automatically.

// HashSet with 8 capacity and 0.75 load factor


HashSet<Integer> numbers = new HashSet<>(8, 0.75);

Here, we have created a hash set named numbers.


Notice, the part new HashSet<>(8, 0.75). Here, the first parameter is capacity, and the second
parameter is loadFactor.
Methods of HashSet
The HashSet class provides various methods that allow us to perform various operations on the
set.
Insert Elements to HashSet
•add() - inserts the specified element to the set
• addAll() - inserts all the elements of the specified collection to the set
Remove Elements
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set
Set Operations
The various methods of the HashSet class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we can use the addAll() method.
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method.
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.

Java LinkedHashSet

LinkedHashSet(C): The LinkedHashSet class of the Java collections framework provides


functionalities of both the hashtable and the linked list data structure.
• It implements the Set interface.

• Elements of LinkedHashSet are stored in hash tables similar to HashSet. However, linked
hash sets maintain a doubly-linked list internally for all of its elements. The linked list
defines the order in which elements are inserted in hash tables.
• LinkedHashSet is a class presents in java.util package which extends (inherits)
from HashSet class and implements from Set.

Create a LinkedHashSet
In order to create a linked hash set, we must import the java.util.LinkedHashSet package first.
Once we import the package, here is how we can create linked hash sets in Java.

// LinkedHashSet with 8 capacity and 0.75 load factor


LinkedHashSet<Integer> numbers = new LinkedHashSet<>(8, 0.75);
Here, we have created a linked hash set named numbers.
Notice, the part new LinkedHashSet<>(8, 0.75). Here, the first parameter is capacity and the
second parameter is loadFactor.
• capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
• loadFactor - The load factor of this hash set is 0.6. This means, whenever our hash table
is filled by 60%, the elements are moved to a new hash table of double the size of the
original hash table.
Default capacity and load factor
It's possible to create a linked hash set without defining its capacity and load factor. For
example,

// LinkedHashSet with default capacity and load factor


LinkedHashSet<Integer> numbers1 = new LinkedHashSet<>();

By default,
• the capacity of the linked hash set will be 16
• the load factor will be 0.75
Insert Elements to LinkedHashSet
• add() - inserts the specified element to the linked hash set
• addAll() - inserts all the elements of the specified collection to the linked hash set
Access LinkedHashSet Elements
To access the elements of a linked hash set, we can use the iterator()method. In order to use this
method, we must import the java.util.Iterator package.
• hasNext() returns true if there is a next element in the linked hash set
• next() returns the next element in the linked hash set
Remove Elements from HashSet
• remove() - removes the specified element from the linked hash set
• removeAll() - removes all the elements from the linked hash set
Set Operations
The various methods of the LinkedHashSet class can also be used to perform various set
operations.
Union of Sets
Two perform the union between two sets, we can use the addAll() method. For example
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method.
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.

Other Methods Of LinkedHashSet

Method Description

clone() Creates a copy of the LinkedHashSet

Searches the LinkedHashSet for the specified element and returns a boolean
contains()
result

isEmpty() Checks if the LinkedHashSet is empty

size() Returns the size of the LinkedHashSet

clear() Removes all the elements from the LinkedHashSet

import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("LinkedHashSet: " + numbers);

// Using the remove() method


boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);

boolean value2 = numbers.removeAll(numbers);


System.out.println("Are all elements removed? " + value2);
}
}
Run Code
Output

LinkedHashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Set Operations
import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("LinkedHashSet1: " + evenNumbers);

LinkedHashSet<Integer> numbers = new LinkedHashSet<>();


numbers.add(1);
numbers.add(3);
System.out.println("LinkedHashSet2: " + numbers);

// Union of two set


numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);

LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();


primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("LinkedHashSet1: " + primeNumbers);
// Intersection of two sets
evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection is: " + evenNumbers);

primeNumbers.add(5);
LinkedHashSet<Integer> oddNumbers = new LinkedHashSet<>();
oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
System.out.println("LinkedHashSet2: " + oddNumbers);
// Difference between LinkedHashSet1 and LinkedHashSet2
primeNumbers.removeAll(oddNumbers);
System.out.println("Difference : " + primeNumbers);

}
}
Output

LinkedHashSet1: [2, 4]
LinkedHashSet2: [1, 3]
Union is: [1, 3, 2, 4]
LinkedHashSet1: [2, 3]
LinkedHashSet2: [2, 4]
Intersection is: [2]
LinkedHashSet1: [2, 3, 5]
LinkedHashSet2: [1, 3, 5]
Difference: [2]

HashSet vs LinkedHashSet: It is exactly same as HashSet including constructors


and methods except the following differences.

HashSet LinkedHashSet
1.The underlying DS is Hash table. 1.The underlying DS is LinkedList and Hash
table
2.Insertion order not preserved. 2. Insertion order preserved.
3.Introducedin1.2v 3.Introducedin1.4v

Note: In general, we can use LinkedHashSet to develop cache based applications


where duplicates are not allowed and insertion order preserved.

Java SortedSet Interface

SortedSet(I): The SortedSet interface of the Java collections framework is used to store
elements with some order in a set.
It extends the Set interface.
SortedSet is the child interface of Set interface.
If we want to represent a group of individual objects as single entity where duplicates
are not allowed but all objects should be inserted according to some sorting order,
then we go for SortedSet.
Class that implements SortedSet
In order to use the functionalities of the SortedSet interface, we need to use the TreeSet class
that implements it.

How to use SortedSet?


To use SortedSet, we must import the java.util.SortedSet package first.

// SortedSet implementation by TreeSet class


SortedSet<String> animals = new TreeSet<>();

Methods of SortedSet
The SortedSet interface includes all the methods of the Set interface. It's because Set is a super
interface of SortedSet.
Besides methods included in the Set interface, the SortedSet interface also includes these
methods:
• comparator() - returns a comparator that can be used to order elements in the
set. return Comparator object that describes underlying sorting technique like
ascending, descending etc. If we are using default natural sorting order, then
we will get null.
• first() - returns the first element of the set
• last() - returns the last element of the set
• headSet(element) - returns all the elements of the set before the specified element
• tailSet(element) - returns all the elements of the set after the specified element including
the specified element
• subSet(element1, element2) - returns all the elements between
the element1 and element2 including element1

Ex: Consider a set as {100,101,104,106,110,115,120}

(a) first() – 100 (b) last–120 (c) headSet(106)–{100,101,104} (d)


tailSet(106)–
{106,110,115,120} (e) subSet(101,115)– {101,104,106,110} (e)comparator()– null

Java TreeSet

The TreeSet class of the Java collections framework provides the functionality of a tree data
structure.
It extends the NavigableSet interface.

Creating a TreeSet

In order to create a tree set, we must import the java.util.TreeSet package first.
Once we import the package, here is how we can create a TreeSet in Java.

TreeSet<Integer> numbers = new TreeSet<>();


Here, we have created a TreeSet without any arguments. In this case, the elements
in TreeSet are sorted naturally (ascending order).
However, we can customize the sorting of elements by using the Comparator interface.

Methods of TreeSet

The TreeSet class provides various methods that allow us to perform various operations on the
set.

Insert Elements to TreeSet

• add() - inserts the specified element to the set


• addAll() - inserts all the elements of the specified collection to the set
For example,
import java.util.TreeSet;

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

TreeSet<Integer> evenNumbers = new TreeSet<>();

// Using the add() method


evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.add(6);
System.out.println("TreeSet: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);

// Using the addAll() method


numbers.addAll(evenNumbers);
System.out.println("New TreeSet: " + numbers);
}
}
Run Code
Output

TreeSet: [2, 4, 6]
New TreeSet: [1, 2, 4, 6]
Access TreeSet Elements

To access the elements of a tree set, we can use the iterator() method. In order to use this
method, we must import java.util.Iterator package. For example,
import java.util.TreeSet;
import java.util.Iterator;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Calling iterator() method


Iterator<Integer> iterate = numbers.iterator();
System.out.print("TreeSet using Iterator: ");
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Run Code
Output

TreeSet: [2, 5, 6]
TreeSet using Iterator: 2, 5, 6,

Remove Elements

• remove() - removes the specified element from the set


• removeAll() - removes all the elements from the set
For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using the remove() method


boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);

// Using the removeAll() method


boolean value2 = numbers.removeAll(numbers);
System.out.println("Are all elements removed? " + value2);
}
}
Run Code
Output

TreeSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Methods for Navigation

Since the TreeSet class implements NavigableSet, it provides various methods to navigate over
the elements of the tree set.
1. first() and last() Methods

• first() - returns the first element of the set


• last() - returns the last element of the set
For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using the first() method


int first = numbers.first();
System.out.println("First Number: " + first);

// Using the last() method


int last = numbers.last();
System.out.println("Last Number: " + last);
}
}
Run Code
Output

TreeSet: [2, 5, 6]
First Number: 2
Last Number: 6

2. ceiling(), floor(), higher() and lower() Methods

• higher(element) - Returns the lowest element among those elements that are greater than
the specified element.
• lower(element) - Returns the greatest element among those elements that are less than
the specified element.
• ceiling(element) - Returns the lowest element among those elements that are greater than
the specified element. If the element passed exists in a tree set, it returns
the element passed as an argument.
• floor(element) - Returns the greatest element among those elements that are less than the
specified element. If the element passed exists in a tree set, it returns the element passed
as an argument.
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using higher()
System.out.println("Using higher: " + numbers.higher(4));

// Using lower()
System.out.println("Using lower: " + numbers.lower(4));

// Using ceiling()
System.out.println("Using ceiling: " + numbers.ceiling(4));

// Using floor()
System.out.println("Using floor: " + numbers.floor(3));

}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Using higher: 5
Using lower: 2
Using ceiling: 4
Using floor: 2

3. pollfirst() and pollLast() Methods

• pollFirst() - returns and removes the first element from the set
• pollLast() - returns and removes the last element from the set
For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using pollFirst()
System.out.println("Removed First Element: " + numbers.pollFirst());

// Using pollLast()
System.out.println("Removed Last Element: " + numbers.pollLast());

System.out.println("New TreeSet: " + numbers);


}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Removed First Element: 2
Removed Last Element: 6
New TreeSet: [4, 5]

4. headSet(), tailSet() and subSet() Methods

headSet(element, booleanValue)

The headSet() method returns all the elements of a tree set before the specified element (which
is passed as an argument).
The booleanValue parameter is optional. Its default value is false.
If true is passed as a booleanValue, the method returns all the elements before the specified
element including the specified element.
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using headSet() with default boolean value


System.out.println("Using headSet without boolean value: " + numbers.headSet(5));

// Using headSet() with specified boolean value


System.out.println("Using headSet with boolean value: " + numbers.headSet(5, true));
}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Using headSet without boolean value: [2, 4]
Using headSet with boolean value: [2, 4, 5]

tailSet(element, booleanValue)

The tailSet() method returns all the elements of a tree set after the specified element (which is
passed as a parameter) including the specified element.
The booleanValue parameter is optional. Its default value is true.
If false is passed as a booleanValue, the method returns all the elements after the
specified element without including the specified element.
For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using tailSet() with default boolean value


System.out.println("Using tailSet without boolean value: " + numbers.tailSet(4));

// Using tailSet() with specified boolean value


System.out.println("Using tailSet with boolean value: " + numbers.tailSet(4, false));
}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Using tailSet without boolean value: [4, 5, 6]
Using tailSet with boolean value: [5, 6]

subSet(e1, bv1, e2, bv2)

The subSet() method returns all the elements between e1 and e2 including e1.
The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default
value of bv2 is false.
If false is passed as bv1, the method returns all the elements between e1 and e2 without
including e1.
If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.
For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using subSet() with default boolean value


System.out.println("Using subSet without boolean value: " + numbers.subSet(4, 6));

// Using subSet() with specified boolean value


System.out.println("Using subSet with boolean value: " + numbers.subSet(4, false, 6,
true));
}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Using subSet without boolean value: [4, 5]
Using subSet with boolean value: [5, 6]

Set Operations

The methods of the TreeSet class can also be used to perform various set operations.
Union of Sets

To perform the union between two sets, we use the addAll() method. For example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("TreeSet2: " + numbers);

// Union of two sets


numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);

}
}
Run Code
Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3]
Union is: [1, 2, 3, 4]
Intersection of Sets

To perform the intersection between two sets, we use the retainAll() method. For example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("TreeSet2: " + numbers);

// Intersection of two sets


numbers.retainAll(evenNumbers);
System.out.println("Intersection is: " + numbers);
}
}
Run Code
Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3]
Intersection is: [2]

Difference of Sets

To calculate the difference between the two sets, we can use the removeAll() method. For
example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("TreeSet2: " + numbers);

// Difference between two sets


numbers.removeAll(evenNumbers);
System.out.println("Difference is: " + numbers);
}
}
Run Code
Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3, 4]
Difference is: [1, 3]

Subset of a Set

To check if a set is a subset of another set or not, we use the containsAll() method. For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("TreeSet1: " + numbers);

TreeSet<Integer> primeNumbers = new TreeSet<>();


primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("TreeSet2: " + primeNumbers);

// Check if primeNumbers is subset of numbers


boolean result = numbers.containsAll(primeNumbers);
System.out.println("Is TreeSet2 subset of TreeSet1? " + result);
}
}
Run Code
Output

TreeSet1: [1, 2, 3, 4]
TreeSet2: [2, 3]
Is TreeSet2 subset of TreeSet1? True

Other Methods of TreeSet

Method Description

clone() Creates a copy of the TreeSet

contains() Searches the TreeSet for the specified element and returns a boolean result

isEmpty() Checks if the TreeSet is empty

size() Returns the size of the TreeSet

clear() Removes all the elements from the TreeSet

TreeSet Vs. HashSet

Both the TreeSet as well as the HashSet implements the Set interface. However, there exist
some differences between them.
• Unlike HashSet, elements in TreeSet are stored in some order. It is
because TreeSet implements the SortedSet interface as well.
• TreeSet provides some methods for easy navigation. For
example, first(), last(), headSet(), tailSet(), etc. It is because TreeSet also implements
the NavigableSet interface.
• HashSet is faster than the TreeSet for basic operations like add, remove, contains and
size.
Java Map Interface

The Map interface of the Java collections framework provides the functionality of the map data
structure.

Map(I):

Map is not child interface of Collection. If we want represent a group of objects as


key value pairs then we should go for Map interface.

Key Value
entry
101 A
102 B
103 C
104 A

Both keys and values are objects only. Duplicate keys are not allowed but
duplicate values are allowed. Each key value pair is called entry. Hence, Map is
considered as a collection of entry objects.

Classes that implement Map

Since Map is an interface, we cannot create objects from it.


In order to use the functionalities of the Map interface, we can use these classes:
• HashMap
• EnumMap
• LinkedHashMap
• WeakHashMap
• TreeMap
These classes are defined in the collections framework and implemented in the Map interface.

Interfaces that extend Map

The Map interface is also extended by these subinterfaces:


• SortedMap
• NavigableMap
• ConcurrentMap

In Java, we must import the java.util.Map package in order to use Map. Once we import the
package, here's how we can create a map.

// Map implementation using HashMap


Map<Key, Value> numbers = new HashMap<>();

In the above code, we have created a Map named numbers. We have used the HashMap class to
implement the Map interface.
Here,

• Key - a unique identifier used to associate each element (value) in a map


• Value - elements associated by keys in a map

Methods of Map

The Map interface includes all the methods of the Collection interface. It is
because Collection is a super interface of Map.
Besides methods available in the Collection interface, the Map interface also includes the
following methods:
• put(K, V) - Inserts the association of a key K and a value V into the map. If the key is
already present, the new value replaces the old value.
• putAll() - Inserts all the entries from the specified map to this map.
• putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the
value V.
• get(K) - Returns the value associated with the specified key K. If the key is not found, it
returns null.
• getOrDefault(K, defaultValue) - Returns the value associated with the specified key K. If
the key is not found, it returns the defaultValue.
• containsKey(K) - Checks if the specified key K is present in the map or not.
• containsValue(V) - Checks if the specified value V is present in the map or not.
• replace(K, V) - Replace the value of the key K with the new specified value V.
• replace(K, oldValue, newValue) - Replaces the value of the key K with the new
value newValue only if the key K is associated with the value oldValue.
• remove(K) - Removes the entry from the map represented by the key K.
• remove(K, V) - Removes the entry from the map that has key K associated with value V.
• keySet() - Returns a set of all the keys present in a map.
• values() - Returns a set of all the values present in a map.
• entrySet() - Returns a set of all the key/value mapping present in a map.

Implementation of the Map Interface

1. Implementing HashMap Class


import java.util.Map;
import java.util.HashMap;

class Main {

public static void main(String[] args) {


// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();

// Insert elements to the map


numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);

// Access keys of the map


System.out.println("Keys: " + numbers.keySet());
// Access values of the map
System.out.println("Values: " + numbers.values());

// Access entries of the map


System.out.println("Entries: " + numbers.entrySet());

// Remove Elements from the map


int value = numbers.remove("Two");
System.out.println("Removed Value: " + value);
}
}
Run Code
Output

Map: {One=1, Two=2}


Keys: [One, Two]
Values: [1, 2]
Entries: [One=1, Two=2]
Removed Value: 2

2. Implementing TreeMap Class


import java.util.Map;
import java.util.TreeMap;

class Main {

public static void main(String[] args) {


// Creating Map using TreeMap
Map<String, Integer> values = new TreeMap<>();

// Insert elements to map


values.put("Second", 2);
values.put("First", 1);
System.out.println("Map using TreeMap: " + values);

// Replacing the values


values.replace("First", 11);
values.replace("Second", 22);
System.out.println("New Map: " + values);

// Remove elements from the map


int removedValue = values.remove("First");
System.out.println("Removed Value: " + removedValue);
}
}
Run Code
Output

Map using TreeMap: {First=1, Second=2}


New Map: {First=11, Second=22}
Removed Value: 11

Java HashMap

The HashMap class of the Java collections framework provides the functionality of the hash
table data structure.
It stores elements in key/value pairs. Here, keys are unique identifiers used to associate
each value on a map.
The HashMap class implements the Map interface.

Java HashMap Implementation

Create a HashMap

In order to create a hash map, we must import the java.util.HashMap package first. Once we
import the package, here is how we can create hashmaps in Java.

// hashMap creation with 8 capacity and 0.6 load factor


HashMap<K, V> numbers = new HashMap<>();

In the above code, we have created a hashmap named numbers. Here, K represents the key type
and V represents the type of values. For example,
HashMap<String, Integer> numbers = new HashMap<>();

Here, the type of keys is String and the type of values is Integer.

Basic Operations on Java HashMap

The HashMap class provides various methods to perform different operations on hashmaps. We
will look at some commonly used arraylist operations in this tutorial:
• Add elements

• Access elements

• Change elements

• Remove elements
import java.util.HashMap;

class Main {
public static void main(String[] args) {
HashMap<Integer, String> languages = new HashMap<>();

languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
System.out.println("HashMap: " + languages);

// get method for get value


String val = language.get(1);
System.out.println(“val at index 1” + val);

// return set view of keys


// using keySet()
System.out.println("Keys: " + languages.keySet());

// return set view of values


// using values()
System.out.println("Values: " + languages.values());

// return set view of key/value pairs


// using entrySet()
System.out.println("Key/Value mappings: " + languages.entrySet());
}
}
Output

HashMap: {1=Java, 2=Python, 3=JavaScript}


Val at index 1 Java
Keys: [1, 2, 3]
Values: [Java, Python, JavaScript]
Key/Value mappings: [1=Java, 2=Python, 3=JavaScript]

1. To add a single element to the hashmap, we use the put() method of the HashMap class.
Here, we are passing the String value One as the key and Integer value 1 as the value to
the put() method.
2. We can use the get() method to access the value from the hashmap. Here,
the get() method takes the key as its argument and returns the
corresponding value associated with the key.
3. We can also access the keys, values, and key/value pairs of the hashmap as set views
using keySet(), values(), and entrySet() methods respectively

Java LinkedHashMap

The LinkedHashMap class of the Java collections framework provides the hash table and linked
list implementation of the Map interface.
The LinkedHashMap interface extends the HashMap class to store its entries in a hash table. It
internally maintains a doubly-linked list among all of its entries to order its entries.
Creating a LinkedHashMap

In order to create a linked hashmap, we must import the java.util.LinkedHashMap package first.
Once we import the package, here is how we can create linked hashmaps in Java.

// LinkedHashMap with initial capacity 8 and load factor 0.6


LinkedHashMap<Key, Value> numbers = new LinkedHashMap<>(8, 0.6f);

In the above code, we have created a linked hashmap named numbers.


Here,

• Key - a unique identifier used to associate each element (value) in a map


• Value - elements associated by the keys in a map
Notice the part new LinkedHashMap<>(8, 0.6). Here, the first parameter is capacity and the
second parameter is loadFactor.
• capacity - The capacity of this linked hashmap is 8. Meaning, it can store 8 entries.
• loadFactor - The load factor of this linked hashmap is 0.6. This means, whenever our
hash map is filled by 60%, the entries are moved to a new hash table of double the size of
the original hash table.
Default capacity and load factor
It's possible to create a linked hashmap without defining its capacity and load factor. For
example,

//LinkedHashMap with default capacity and load factor


LinkedHashMap<Key, Value> numbers1 = new LinkedHashMap<>();

By default,

• the capacity of the linked hashmap will be 16

• the load factor will be 0.75

Methods of LinkedHashMap

The LinkedHashMap class provides methods that allow us to perform various operations on the
map.
Insert Elements to LinkedHashMap

• put() - inserts the specified key/value mapping to the map


• putAll() - inserts all the entries from the specified map to this map
• putIfAbsent() - inserts the specified key/value mapping to the map if the specified key is
not present in the map

Access LinkedHashMap Elements

1. Using entrySet(), keySet() and values()


• entrySet() - returns a set of all the key/value mapping of the map
• keySet() - returns a set of all the keys of the map
• values() - returns a set of all the values of the map
2. Using get() and getOrDefault()
• get() - Returns the value associated with the specified key. If the key is not found, it
returns null.
• getOrDefault() - Returns the value associated with the specified key. If the key is not
found, it returns the specified default value.

Remove LinkedHashMap Elements

• remove(key) - returns and removes the entry associated with the specified key from the
map
• remove(key, value) - removes the entry from the map only if the specified key mapped to
be the specified value and return a boolean value

Other Methods of LinkedHashMap

Method Description

clear() removes all the entries from the map

containsKey() checks if the map contains the specified key and returns a boolean value

checks if the map contains the specified value and returns a boolean
containsValue()
value
size() returns the size of the map

isEmpty() checks if the map is empty and returns a boolean value


import java.util.LinkedHashMap;

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

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


numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("LinkedHashMap: " + numbers);

// Using get()
int value1 = numbers.get("Three");
System.out.println("Returned Number: " + value1);

// Using getOrDefault()
int value2 = numbers.getOrDefault("Five", 5);
System.out.println("Returned Number: " + value2);
}
}
Output

LinkedHashMap: {One=1, Two=2, Three=3}


Returned Number: 3
Returned Number: 5

Java TreeMap

The TreeMap class of the Java collections framework provides the tree data structure
implementation.
It implements the NavigableMap interface.
Creating a TreeMap

In order to create a TreeMap, we must import the java.util.TreeMap package first. Once we
import the package, here is how we can create a TreeMap in Java.

TreeMap<Key, Value> numbers = new TreeMap<>();

In the above code, we have created a TreeMap named numbers without any arguments. In this
case, the elements in TreeMap are sorted naturally (ascending order).
However, we can customize the sorting of elements by using the Comparator interface. We will
learn about it later in this tutorial.
Here,

• Key - a unique identifier used to associate each element (value) in a map


• Value - elements associated by keys in a map

Methods of TreeMap

The TreeMap class provides various methods that allow us to perform operations on the map.

Insert Elements to TreeMap

• put() - inserts the specified key/value mapping (entry) to the map


• putAll() - inserts all the entries from specified map to this map
• putIfAbsent() - inserts the specified key/value mapping to the map if the specified key is
not present in the map

Access TreeMap Elements

1. Using entrySet(), keySet() and values()


• entrySet() - returns a set of all the key/values mapping (entry) of a treemap
• keySet() - returns a set of all the keys of a tree map
• values() - returns a set of all the maps of a tree map
2. Using get() and getOrDefault()
• get() - Returns the value associated with the specified key. Returns null if the key is not
found.
• getOrDefault() - Returns the value associated with the specified key. Returns the
specified default value if the key is not found.

Remove TeeMap Elements

• remove(key) - returns and removes the entry associated with the specified key from a
TreeMap
• remove(key, value) - removes the entry from the map only if the specified key is
associated with the specified value and returns a boolean value
import java.util.TreeMap;

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

TreeMap<String, Integer> numbers = new TreeMap<>();


numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("TreeMap: " + numbers);

// Using get()
int value1 = numbers.get("Three");
System.out.println("Using get(): " + value1);

// Using getOrDefault()
int value2 = numbers.getOrDefault("Five", 5);
System.out.println("Using getOrDefault(): " + value2);
}
}

Output

TreeMap: {One=1, Three=3, Two=2}


Using get(): 3
Using getOrDefault(): 5

• Here, the getOrDefault() method does not find the key Five. Hence it returns the
specified default value 5.

Methods for Navigation

Since the TreeMap class implements NavigableMap, it provides various methods to navigate
over the elements of the treemap.
1. First and Last Methods

• firstKey() - returns the first key of the map


• firstEntry() - returns the key/value mapping of the first key of the map
• lastKey() - returns the last key of the map
• lastEntry() - returns the key/value mapping of the last key of the map
2. Ceiling, Floor, Higher and Lower Methods

• higherKey() - Returns the lowest key among those keys that are greater than the specified
key.
• higherEntry() - Returns an entry associated with a key that is lowest among all those
keys greater than the specified key.
• lowerKey() - Returns the greatest key among all those keys that are less than the
specified key.
• lowerEntry() - Returns an entry associated with a key that is greatest among all those
keys that are less than the specified key.
• ceilingKey() - Returns the lowest key among those keys that are greater than the specified
key. If the key passed as an argument is present in the map, it returns that key.
• ceilingEntry() - Returns an entry associated with a key that is lowest among those keys
that are greater than the specified key. It an entry associated with the key passed an
argument is present in the map, it returns the entry associated with that key.
• floorKey() - Returns the greatest key among those keys that are less than the specified
key. If the key passed as an argument is present, it returns that key.
• floorEntry() - Returns an entry associated with a key that is greatest among those keys
that are less than the specified key. If the key passed as argument is present, it returns that
key.
3. pollFirstEntry() and pollLastEntry() Methods

• pollFirstEntry() - returns and removes the entry associated with the first key of the map
• pollLastEntry() - returns and removes the entry associated with the last key of the map
4. headMap(), tailMap() and subMap() Methods

headMap(key, booleanValue)
The headMap() method returns all the key/value pairs of a treemap before the
specified key (which is passed as an argument).
The booleanValue parameter is optional. Its default value is false.
If true is passed as a booleanValue, the method also includes the key/value pair of
the key which is passed as an argument.

Hashtable class in java

In java, the package java.util contains a class called Hashtable which works like a HashMap but
it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with a
value. Any non-null object can be used as a key or as a value. We can use the key to retrieve the
value back when needed.
The Hashtable class is no longer in use, it is obsolete. The alternate class is HashMap.
The Hashtable class is a concrete class of Dictionary.
The Hashtable class is synchronized.
The Hashtable does no allow null key or value.
The Hashtable has the initial default capacity 11.
The Hashtable class in java has the following constructors.

S. No. Constructor with Description

1 Hashtable( )

It creates an empty hashtable with the default initial capacity 11.

2 Hashtable(int capacity)
It creates an empty hashtable with the specified initial capacity.

3 Hashtable(int capacity, float loadFactor)


It creates an empty hashtable with the specified initial capacity and loading factor.

4 Hashtable(Map m)
It creates a hashtable containing elements of Map m.

The Hashtable class in java has the following methods.

S.
No. Methods with Description

1 V put(K key, V value)

It inserts the specified key and value into the hash table.

2 void putAll(Map m))


It inserts all the elements of Map m into the invoking Hashtable.

3 V putIfAbsent(K key, V value)


If the specified key is not already associated with a value associates it with the given value
the current value.

4 V getOrDefault(Object key, V defaultValue)


It returns the value associated with given key; or defaultValue if the hashtable contains no
S.
No. Methods with Description

5 V get(Object key)
It returns the value associated with the given key.

6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.

7 Set keySet()
Returns a set view of the keys of the hashtable.

8 Collection values()
It returns a collection view of the values contained in the Hashtable.

9 Enumeration elements()
Returns an enumeration of the values of the hashtable.

10 Set entrySet()
It returns a set view of the mappings contained in the hashtable.

11 int hashCode()
It returns the hash code of the hashtable.

12 Object clone()
It returns a shallow copy of the Hashtable.

13 V remove(Object key)
It returns the value associated with given key and removes the same.

14 boolean remove(Object key, Object value)


It removes the specified values with the associated specified keys from the hashtable.

15 boolean contains(Object value)


It returns true if the specified value found within the hash table, else return false.

16 boolean containsValue(Object value)


It returns true if the specified value found within the hash table, else return false.
S.
No. Methods with Description

17 boolean containsKey(Object key)


It returns true if the specified key found within the hash table, else return false.

18 V replace(K key, V value)


It replaces the specified value for a specified key.

19 boolean replace(K key, V oldValue, V newValue)


It replaces the old value with the new value for a specified key.

20 void replaceAll(BiFunction function)


It replaces each entry's value with the result of invoking the given function on that entry u
processed or the function throws an exception.

21 void rehash()
It is used to increase the size of the hash table and rehashes all of its keys.

22 String toString()
It returns a string representation of the Hashtable object.

23 V merge(K key, V value, BiFunction remappingFunction)


If the specified key is not already associated with a value or is associated with null, associ
value.

24 void forEach(BiConsumer action)


It performs the given action for each entry in the map until all entries have been processed
exception.

25 boolean isEmpty( )
It returns true if Hashtable has no elements; otherwise returns false.

26 int size( )
It returns the total number of elements in the Hashtable.

27 void clear()
It is used to remove all the lements of a Hashtable.
S.
No. Methods with Description

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

Example

import java.util.*;

public class HashtableExample {

public static void main(String[] args) {

Random num = new Random();


Hashtable table = new Hashtable();

//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));

System.out.println("Hashtable => " + table);

//get(key)
System.out.println("\nValue associated with key 3 => " + table.get(3));
System.out.println("Value associated with key 30 => " + table.get(30));

//keySet()
System.out.println("\nKeys => " + table.keySet());

//values()
System.out.println("\nValues => " + table.values());
//entrySet()
System.out.println("\nKey, Value pairs as a set => " + table.entrySet());

//hashCode()
System.out.println("\nHash code => " + table.hashCode());

//hashCode()
System.out.println("\nTotal number of elements => " + table.size());

//isEmpty()
System.out.println("\nEmpty status of Hashtable => " + table.isEmpty());
}
}

When we execute the above code, it produce the following output.


Java Collections sort()

Java Collections class provides us with a very convenient method Collections.sort() to sort
all List implementations such as LinkedList and ArrayList. There are two
overloaded Collections.sort() methods, which are:
1. sort(List list): Sorts the elements of the List in ascending order of their natural ordering.
2. sort(List list, Comparator c): Sorts the elements of the list according to the order induced
by the comparator.
Note that the above methods signature use generics but I have removed them here for simplicity
in reading. Let us one by one dig into how and when we can use both these methods.

Java Collections sort(List list)


Consider an ArrayList of String:

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


fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Grape");

Now, we will sort it using Collections.sort():

Collections.sort(fruits);
// Print the sorted list
System.out.println(fruits);
The output of this program will be:

[Apple, Banana, Grape, Orange]

Hence, we can see that Collections.sort() has sorted the list of String in Lexical order. And it
does not return anything. What if we have a list of custom objects? Of course, we can sort them
as well. Consider a class Fruit:
package com.journaldev.collections;
public class Fruit{
private int id;
private String name;
private String taste;

Fruit(int id, String name, String taste){


this.id=id;
this.name=name;
this.taste=taste;
}
}

Let’s create a list of Fruits:

List<Fruit> fruitList=new ArrayList<Fruit>();


Fruit apple=new Fruit(1, "Apple", "Sweet");
Fruit orange=new Fruit(2, "Orange", "Sour");
Fruit banana=new Fruit(4, "Banana", "Sweet");
Fruit grape=new Fruit(3, "Grape", "Sweet and Sour");

fruitList.add(apple);
fruitList.add(orange);
fruitList.add(banana);
fruitList.add(grape);
In order to sort this list, if we directly use the Collections.sort(List list), it will give a Compile
Time Error because there is no natural ordering defined for the Fruit objects. So, it doesn’t know

how to sort this list. For


objects to have a natural order they must implement the interface java.lang.Comparable.
The Comparable interface has a method compareTo(), which returns a negative, 0, a positive if
the current value is less than, equal to, or greater than the value we are comparing with,
respectively. Let’s enhance the Fruit class to implement Comparable interface. We are defining
that the natural order of sorting is based on the “id” field of Fruit:
package com.journaldev.collections;
public class Fruit implements Comparable<Object>{
private int id;
private String name;
private String taste;

Fruit(int id, String name, String taste){


this.id=id;
this.name=name;
this.taste=taste;
}
@Override
public int compareTo(Object o) {
Fruit f = (Fruit) o;
return this.id - f.id ;
}
}
Now that we have implemented Comparable, we can sort the list without any errors:
Collections.sort(fruitList);
fruitList.forEach(fruit -> {
System.out.println(fruit.getId() + " " + fruit.getName() + " " +
fruit.getTaste());
});

The output will be as below:


1 Apple Sweet
2 Orange Sour
3 Grape Sweet and Sour
4 Banana Sweet

Java Collections sort(List list, Comparator c)

In order to define a custom logic for sorting, which is different from the natural ordering of the
elements, we can implement the java.util.Comparator interface and pass an instance of it as the
second argument of sort(). Let’s consider that we want to define the ordering based on the
“name” field of the Fruit. We implement the Comparator, and in its compare() method, we need
to write the logic for comparison:
package com.journaldev.collections;

class SortByName implements Comparator<Fruit> {


@Override
public int compare(Fruit a, Fruit b) {
return a.getName().compareTo(b.getName());
}
}

Now, we can sort it using this comparator:

Collections.sort(fruitList, new SortByName());


The output will be as below:

1 Apple Sweet
4 Banana Sweet
3 Grape Sweet and Sour
2 Orange Sour

Instead of writing new class for Comparator, using lambda function, we can provide sorting
logic at runtime as well:

Collections.sort(fruitList, (a, b) -> {


return a.getName().compareTo(b.getName());
});

Java Collections.reverseOrder

By default, Collection.sort performs the sorting in ascending order. If we want to sort the
elements in reverse order we could use following methods:
1. reverseOrder(): Returns a Comparator that imposes the reverse of natural ordering of
elements of the collection.
2. reverseOrder(Comparator cmp): Returns a Comparator that imposes reverse ordering of
the specified comparator.

Here are the examples for both these methods:


Java Collections reverseOrder() example
Collections.sort(fruits, Collections.reverseOrder());
System.out.println(fruits);

It’ll output the fruits in reverse alphabetical order:


[Orange, Grape, Banana, Apple]

Java Comparable interface

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

compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current object with the specified
object. It returns

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.

Ex: obj1.compareTo(obj2); //compareTo() method is used to compare two objects.

obj1- the object which is to be inserted, obj2 the object which is already inserted.

(a)returns -ve value if obj1 comes before obj2


(b)returns +ve value if obj1comes after obj2
(c)returns 0 if obj1is equals to obj2

Note:(i) SOP(“A”.compareTo(null));//RE:NullPointerException

(ii) If we are depending on default natural sorting order then while adding objects
into the TreeSet JVM will call comapreTo() method.
Ex: TreeSet t=new TreeSet();
t.add(“K”); //It is the1st element, hence comparison is not required.
t.add(“Z”); //“Z”.compareTo(“K”) –returns -ve value i.e. Z should come after K
t.add(“A”); //“A”.compareTo(“K”)– returns +ve value i.e. A should come before K
t.add(“A”); // “A”.compareTo(“K”) – returns +ve value i.e. A should come before K
and “A”.compareTo(“A”) – returns 0 i.e. Both are equal. Hence, “A” is not inserted for
2nd time. SOP(t); // [A,K,Z]

Java Comparator interface

Java Comparator interface is used to order the objects of a user-defined class. Comparator is
present in java.util package

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface


Method Description

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

public boolean equals(Object obj) It is used to compare the current object with the specified
Collections class

Collections class provides static methods for sorting the elements of a collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type elements
also.

Method of Collections class for sorting List elements

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

Ex: compare(obj1,obj2); //compare() method is used to compare two objects.


obj1the object which is to be inserted, obj2 the object which is already inserted.

(a)returns -ve value if obj1 comes before obj2


(b)returns +ve value if obj1comes after obj2
(c)returns 0 if obj1is equals to obj2

Comparable vs Comparator:

Comparison of Comparable Comparator:

Comparable(I) Comparator(I)
1.Comparable meant for default natural sorting 1.Comparator meant for customized sorting
order. order.
2.Comparable present in java.lang package. 2.Comparable present in java.util package.
3.It contains only one method i.e. compareTo() 3. It contains 2 methods i.compare()
ii.equals()
4.By default all wrapper classes and String 4. If default sorting order not
class implement Comparable interface.
available or if we are not
satisfied with default natural
sorting order then we can go
for customized sorting by using
Comparator.

Java Properties
Properties(C): In our program, if anything which changes frequently (like
username, password, mail id, mobile no) are not recommended to hard code in Java
program because if there is any change to reflect that change recompilation, rebuild,
and redeploy application are required. Even some times server restart is also required
which creates a big business impact to the client.

We can overcome this problem by using properties file, such type of variable things
we have to configure in the properties file. From that properties file we have to read
into Java program and we can use those properties.
The main advantage of this approach is if there is a change in properties file to reflect
that change just redeployment is enough which won’t create any business impact to
the client.

We can use Java properties object to hold properties which are coming from properties file.
The Java Properties class is a class which represents a persistent set of properties. The Properties
can be saved to a stream or loaded from a stream. It belongs to java.util package.

Features of Properties class:


• Properties is a subclass of Hashtable.
• It is used to maintain a list of values in which the key is a string and the value is also a
string i.e; it can be used to store and retrieve string type data from the properties file.
• Properties class can specify other properties list as it’s the default. If a particular key
property is not present in the original Properties list, the default properties will be
searched.
• Properties object does not require external synchronization and Multiple threads can share
a single Properties object.
• Also, it can be used to retrieve the properties of the system.
• This class is thread-safe; multiple threads can share a single Properties object without the
need for external synchronization.

Declaration
public class Properties extends Hashtable<Object,Object>
Fields

Following are the fields for java.util.Properties class −

protected Properties defaults − This is the property list that contains default values for any keys
not found in this property list.

Constructors of Properties

1. Properties(): This creates a Properties object that has no default values.


Properties p = new Properties();
2. Properties(Properties propDefault): The second creates an object that
uses propDefault for its default value.
Properties p = new Properties(Properties propDefault);
Example 1: The below program shows how to use Properties class to get information from the
properties file.
Let us create a properties file and name it as db.properties.
username = abc
password = xyz

db.properties
// Java program to demonstrate Properties class to get
// information from the properties file

import java.util.*;
import java.io.*;
public class MYProp {
public static void main(String[] args) throws Exception
{
// create a reader object on the properties file
FileReader reader = new FileReader("db.properties");

// create properties object


Properties p = new Properties();

// Add a wrapper around reader object


p.load(reader);

// access properties data


System.out.println(p.getProperty("username"));
System.out.println(p.getProperty("password"));
}
}

Sr.No. Method & Description


String getProperty(String key)
1 This method searches for the property with the specified key in this
property list.

void list(PrintStream out)


2
This method prints this property list out to the specified output stream.

void load(InputStream inStream)


3 This method reads a property list (key and element pairs) from the input
byte stream.

Object setProperty(String key, String value)


4
This method calls the Hashtable method put.

void store(OutputStream out, String comments)


The method writes this property list (key and element pairs) in this
5
Properties table to the output stream in a format suitable for loading into a
Properties table using the load(InputStream) method.

6 Set<String> stringPropertyNames()
This method returns a set of keys in this property list where the key and its
corresponding value are strings, including distinct keys in the default
property list if a key of the same name has not already been found from
the main properties list.

You might also like