Unit IV-oop Java-Part II
Unit IV-oop Java-Part II
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.
• HashSet
• LinkedHashSet
• TreeSet
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)
The HashSet class of the Java Collections framework provides the functionalities of the hash
table data structure.
It implements the Set interface.
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
class Main {
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
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.
Java LinkedHashSet
• 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.
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.
Method Description
Searches the LinkedHashSet for the specified element and returns a boolean
contains()
result
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);
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);
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 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
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.
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
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.
Methods of TreeSet
The TreeSet class provides various methods that allow us to perform various operations on the
set.
class Main {
public static void main(String[] args) {
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);
TreeSet: [2, 5, 6]
TreeSet using Iterator: 2, 5, 6,
Remove Elements
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);
TreeSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true
Since the TreeSet class implements NavigableSet, it provides various methods to navigate over
the elements of the tree set.
1. first() and last() Methods
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);
TreeSet: [2, 5, 6]
First Number: 2
Last Number: 6
• 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
• 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());
TreeSet: [2, 4, 5, 6]
Removed First Element: 2
Removed Last Element: 6
New TreeSet: [4, 5]
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);
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);
TreeSet: [2, 4, 5, 6]
Using tailSet without boolean value: [4, 5, 6]
Using tailSet with boolean value: [5, 6]
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);
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);
}
}
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);
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);
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);
TreeSet1: [1, 2, 3, 4]
TreeSet2: [2, 3]
Is TreeSet2 subset of TreeSet1? True
Method Description
contains() Searches the TreeSet for the specified element and returns a boolean result
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):
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.
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.
In the above code, we have created a Map named numbers. We have used the HashMap class to
implement the Map interface.
Here,
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.
class Main {
class Main {
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.
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.
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.
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);
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.
By default,
Methods of LinkedHashMap
The LinkedHashMap class provides methods that allow us to perform various operations on the
map.
Insert Elements to LinkedHashMap
• 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
Method Description
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
class Main {
public static void main(String[] args) {
// 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
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.
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,
Methods of TreeMap
The TreeMap class provides various methods that allow us to perform operations on the map.
• 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) {
// 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
• Here, the getOrDefault() method does not find the key Five. Hence it returns the
specified default value 5.
Since the TreeMap class implements NavigableMap, it provides various methods to navigate
over the elements of the treemap.
1. First and Last 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.
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.
1 Hashtable( )
2 Hashtable(int capacity)
It creates an empty hashtable with the specified initial capacity.
4 Hashtable(Map m)
It creates a hashtable containing elements of Map m.
S.
No. Methods with Description
It inserts the specified key and value into the hash table.
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.
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.
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.*;
//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));
//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());
}
}
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.
Collections.sort(fruits);
// Print the sorted list
System.out.println(fruits);
The output of this program will be:
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;
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
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;
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:
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.
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.
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.
obj1- the object which is to be inserted, obj2 the object which is already inserted.
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 is used to order the objects of a user-defined class. Comparator is
present in java.util package
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.
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.
public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.
Comparable vs 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.
Declaration
public class Properties extends Hashtable<Object,Object>
Fields
protected Properties defaults − This is the property list that contains default values for any keys
not found in this property list.
Constructors of Properties
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");
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.