UNIT 4 Part B

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Java Map Interface

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

Working of Map

In Java, elements of Map are stored in key/value pairs. Keys are unique values
associated with individual Values.
A map cannot contain duplicate keys. And, each key is associated with a single
value.

We can access and modify values using the keys associated with them.
In the above diagram, we have values: United States, Brazil, and Spain. And
we have corresponding keys: us, br, and es.
Now, we can access those values using their corresponding keys.

Note: The Map interface maintains 3 different sets:


 the set of keys
 the set of values
 the set of key/value associations (mapping).
Hence we can access keys, values, and associations individually.

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.
Java
Map Subclasses

Interfaces that extend Map


The Map interface is also extended by these subinterfaces:
 SortedMap
 NavigableMap
 ConcurrentMap

Java Map Subinterfaces

How to use Map?

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:

1. 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.

2. putAll() - Inserts all the entries from the specified map to this map.

3. putIfAbsent(K, V) - Inserts the association if the key K is not already


associated with the value V.

4. get(K) - Returns the value associated with the specified key K. If the key is
not found, it returns null.

5. containsKey(K) - Checks if the specified key K is present in the map or not.

6. containsValue(V) - Checks if the specified value V is present in the map or


not.

7. replace(K, V) - Replace the value of the key K with the new specified
value V.

8. 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.
9. remove(K) - Removes the entry from the map represented by the key K.
10. remove(K, V) - Removes the entry from the map that has key K associated
with value V.
11. keySet() - Returns a set of all the keys present in a map.
12. values() - Returns a set of all the values present in a map.
13. 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

To learn more about HashMap, visit Java HashMap.

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.

Example 1: Create HashMap in Java


import java.util.HashMap;

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

// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();

// add elements to hashmap


languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
System.out.println("HashMap: " + languages);
}
}
Run Code
Output

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

In the above example, we have created a HashMap named languages.


Here, we have used the put() method to add elements to the hashmap. We will
learn more about the put() method later in this tutorial.

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

1. Add elements to a HashMap


To add a single element to the hashmap, we use the put() method of
the HashMap class. For example,
import java.util.HashMap;

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

// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();

System.out.println("Initial HashMap: " + numbers);


// put() method to add elements
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("HashMap after put(): " + numbers);
}
}
Run Code
Output

Initial HashMap: {}
HashMap after put(): {One=1, Two=2, Three=3}

In the above example, we have created a HashMap named numbers. Here, we have
used the put() method to add elements to numbers.
Notice the statement,

numbers.put("One", 1);

Here, we are passing the String value One as the key and Integer value 1 as the
value to the put() method.

2. Access HashMap Elements

We can use the get() method to access the value from the hashmap. For example,

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 to get value


String value = languages.get(1);
System.out.println("Value at index 1: " + value);
}
}
Run Code
Output

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


Value at index 1: Java

In the above example, notice the expression,

languages.get(1);

Here, the get() method takes the key as its argument and returns the
corresponding value associated with the key.

We can also access the keys, values, and key/value pairs of the hashmap as set
views using keySet(), values(), and entrySet() methods respectively. For
example,
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);

// 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());
}
}
Run Code
Output

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


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

In the above example, we have created a hashmap named languages. Here, we


are accessing the keys, values, and key/value mappings from the hashmap.

3. Change HashMap Value


We can use the replace() method to change the value associated with a key in a
hashmap. For example,
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("Original HashMap: " + languages);

// change element with key 2


languages.replace(2, "C++");
System.out.println("HashMap using replace(): " + languages);
}
}
Run Code
Output

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


HashMap using replace(): {1=Java, 2=C++, 3=JavaScript}

In the above example, we have created a hashmap named languages. Notice the
expression,

languages.replace(2, "C++");

Here, we are changing the value referred to by key 2 with the new value C++.
The HashMap class also provides some variations of the replace() method.

4. Remove HashMap Elements


To remove elements from a hashmap, we can use the remove() method. For
example,
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);

// remove element associated with key 2


String value = languages.remove(2);
System.out.println("Removed value: " + value);

System.out.println("Updated HashMap: " + languages);


}
}
Run Code
Output

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


Removed value: Python
Updated HashMap: {1=Java, 3=JavaScript}

Here, the remove() method takes the key as its parameter. It then returns
the value associated with the key and removes the entry.
We can also remove the entry only under certain conditions. For example,

remove(2, "C++");

Here, the remove() method only removes the entry if the key 2 is associated with
the value C++. Since 2 is not associated with C++, it doesn't remove the entry.
To learn more, visit Java HashMap remove().

Other Methods of HashMap


Method Description

clear() removes all mappings from the HashMap

compute() computes a new value for the specified key

computeIfAbsent() computes value if a mapping for the key is not present

computeIfPresent() computes a value for mapping if the key is present

merge() merges the specified mapping to the HashMap

clone() makes the copy of the HashMap


containsKey() checks if the specified key is present in Hashmap

containsValue() checks if Hashmap contains the specified value

size() returns the number of items in HashMap

checks if the Hashmap is empty


isEmpty()

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
Note: The LinkedHashMap class also allows us to define the order of its entries. For
example

// LinkedHashMap with specified order


LinkedHashMap<Key, Value> numbers2 = new LinkedHashMap<>(capacity,
loadFactor, accessOrder);

Here, accessOrder is a boolean value. Its default value is false. In this case
entries in the linked hashmap are ordered on the basis of their insertion order.
However, if true is passed as accessOrder, entries in the linked hashmap will be
ordered from least-recently accessed to most-recently accessed.

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
For example,
import java.util.LinkedHashMap;

class Main {
public static void main(String[] args) {
// Creating LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new
LinkedHashMap<>();

// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("Original LinkedHashMap: " +
evenNumbers);

// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
System.out.println("Updated LinkedHashMap(): " +
evenNumbers);

//Creating LinkedHashMap of numbers


LinkedHashMap<String, Integer> numbers = new
LinkedHashMap<>();
numbers.put("One", 1);

// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("New LinkedHashMap: " + numbers);
}
}
Run Code
Output

Original LinkedHashMap: {Two=2, Four=4}


Updated LinkedHashMap: {Two=2, Four=4, Six=6}
New LinkedHashMap: {One=1, Two=2, Four=4, Six=6}

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
For example,
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 entrySet()
System.out.println("Key/Value mappings: " +
numbers.entrySet());

// Using keySet()
System.out.println("Keys: " + numbers.keySet());

// Using values()
System.out.println("Values: " + numbers.values());
}
}
Run Code
Output

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


Key/Value mappings: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]

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.

For example,
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);
}
}
Run Code
Output

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


Returned Number: 3
Returned Number: 5

Removed 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
For example,
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);

// remove method with single parameter


int value = numbers.remove("Two");
System.out.println("Removed value: " + value);

// remove method with two parameters


boolean result = numbers.remove("Three", 3);
System.out.println("Is the entry Three removed? " + result);

System.out.println("Updated LinkedHashMap: " + numbers);


}
}
Run Code
Output

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


Removed value: 2
Is the entry {Three=3} removed? True
Updated LinkedHashMap: {One=1}

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

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

size() returns the size of the map

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

LinkedHashMap Vs. HashMap\

Both the LinkedHashMap and the HashMap implements the Map interface. However,
there exist some differences between them.
 LinkedHashMap maintains a doubly-linked list internally. Due to this, it maintains the
insertion order of its elements.
 The LinkedHashMap class requires more storage than HashMap. This is
because LinkedHashMap maintains linked lists internally.
 The performance of LinkedHashMap is slower than HashMap.

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
For example,
import java.util.TreeMap;

class Main {
public static void main(String[] args) {
// Creating TreeMap of even numbers
TreeMap<String, Integer> evenNumbers = new TreeMap<>();

// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);

// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
System.out.println("TreeMap of even numbers: " +
evenNumbers);

//Creating TreeMap of numbers


TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("One", 1);

// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("TreeMap of numbers: " + numbers);
}
}
Run Code
Output

TreeMap of even numbers: {Four=4, Six=6, Two=2}


TreeMap of numbers: {Four=4, One=1, Six=6, Two=2}

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
For example,
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 entrySet()
System.out.println("Key/Value mappings: " +
numbers.entrySet());

// Using keySet()
System.out.println("Keys: " + numbers.keySet());

// Using values()
System.out.println("Values: " + numbers.values());
}
}
Run Code
Output

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


Key/Value mappings: [One=1, Three=3, Two=2]
Keys: [One, Three, Two]
Values: [1, 3, 2]

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.
For example,
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);
}
}
Run Code
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.

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
For example,
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);

// remove method with single parameter


int value = numbers.remove("Two");
System.out.println("Removed value: " + value);

// remove method with two parameters


boolean result = numbers.remove("Three", 3);
System.out.println("Is the entry {Three=3} removed? " +
result);

System.out.println("Updated TreeMap: " + numbers);


}
}
Run Code
Output

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


Removed value = 2
Is the entry {Three=3} removed? True
Updated TreeMap: {One=1}

Replace TreeMap Elements


 replace(key, value) - replaces the value mapped by the specified key with the
new value
 replace(key, old, new) - replaces the old value with the new value only if the old
value is already associated with the specified key
 replaceAll(function) - replaces each value of the map with the result of the
specified function
For example,
import java.util.TreeMap;

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

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


numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("Original TreeMap: " + numbers);

// Using replace()
numbers.replace("Second", 22);
numbers.replace("Third", 3, 33);
System.out.println("TreeMap using replace: " + numbers);

// Using replaceAll()
numbers.replaceAll((key, oldValue) -> oldValue + 2);
System.out.println("TreeMap using replaceAll: " + numbers);
}
}
Run Code
Output

Original TreeMap: {First=1, Second=2, Third=3}


TreeMap using replace(): {First=1, Second=22, Third=33}
TreeMap using replaceAll(): {First=3, Second=24, Third=35}

In the above program notice the statement

numbers.replaceAll((key, oldValue) -> oldValue + 2);


Here, we have passed a lambda expression as an argument.
The replaceAll() method accesses all the entries of the map. It then replaces all
the elements with the new values (returned from the lambda expression).

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
For example,
import java.util.TreeMap;

class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("TreeMap: " + numbers);

// Using the firstKey() method


String firstKey = numbers.firstKey();
System.out.println("First Key: " + firstKey);

// Using the lastKey() method


String lastKey = numbers.lastKey();
System.out.println("Last Key: " + lastKey);

// Using firstEntry() method


System.out.println("First Entry: " + numbers.firstEntry());

// Using the lastEntry() method


System.out.println("Last Entry: " + numbers.lastEntry());
}
}
Run Code
Output

TreeMap: {First=1, Second=2, Third=3}


First Key: First
Last Key: Third
First Entry: First=1
Last Entry: Third=3

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.
For example,
import java.util.TreeMap;

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

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


numbers.put("First", 1);
numbers.put("Second", 5);
numbers.put("Third", 4);
numbers.put("Fourth", 6);
System.out.println("TreeMap: " + numbers);

// Using higher()
System.out.println("Using higherKey(): " +
numbers.higherKey("Fourth"));
System.out.println("Using higherEntry(): " +
numbers.higherEntry("Fourth"));

// Using lower()
System.out.println("\nUsing lowerKey(): " +
numbers.lowerKey("Fourth"));
System.out.println("Using lowerEntry(): " +
numbers.lowerEntry("Fourth"));

// Using ceiling()
System.out.println("\nUsing ceilingKey(): " +
numbers.ceilingKey("Fourth"));
System.out.println("Using ceilingEntry(): " +
numbers.ceilingEntry("Fourth"));

// Using floor()
System.out.println("\nUsing floorKey(): " +
numbers.floorKey("Fourth"));
System.out.println("Using floorEntry(): " +
numbers.floorEntry("Fourth"));

}
}
Run Code
Output

TreeMap: {First=1, Fourth=6, Second=5, Third=4}


Using higherKey(): Second
Using higherEntry(): Second=5

Using lowerKey(): First


Using lowerEntry(): First=1

Using ceilingKey(): Fourth


Using ceilingEntry(): Fourth=6

Using floorkey(): Fourth


Using floorEntry(): Fourth=6

Other Methods of TreeMap


Method Description

clone() Creates a copy of the TreeMap

containsKey() Searches the TreeMap for the specified key and returns a boolean result
containsValue() Searches the TreeMap for the specified value and returns a boolean result

size() Returns the size of the TreeMap

clear() Removes all the entries from the TreeMap

TreeMap Comparator
In all the examples above, treemap elements are sorted naturally (in ascending
order). However, we can also customize the ordering of keys.
For this, we need to create our own comparator class based on which keys in a
treemap are sorted. For example,
import java.util.TreeMap;
import java.util.Comparator;

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

// Creating a treemap with a customized comparator


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

numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
}

// Creating a comparator class


public static class CustomComparator implements
Comparator<String> {

@Override
public int compare(String number1, String number2) {
int value = number1.compareTo(number2);

// elements are sorted in reverse order


if (value > 0) {
return -1;
}
else if (value < 0) {
return 1;
}
else {
return 0;
}
}
}
}
Run Code
Output

TreeMap: {Third=3, Second=2, Fourth=4, First=1}

In the above example, we have created a treemap


passing CustomComparator class as an argument.
The CustomComparator class implements the Comparator interface.
We then override the compare() method to sort elements in reverse order.

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.

We can sort the elements of:


1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class

Collections class provides static methods for sorting the elements of collections. 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.
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.

Method of Collections class for sorting List elements

public void sort(List list): It is used to sort the elements of List. List elements must
be of the Comparable type.

Note: String class and Wrapper classes implement the Comparable interface by
default. So if you store the objects of string or wrapper classes in a list, set or map, it
will be Comparable by default.

Java Comparable Example

File: TestSort1.java
1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }
105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparable Example: reverse order

File: TestSort2.java
1. import java.util.*;
2. public class TestSort2{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }
106 Ajay 27
101 Vijay 23
105 Jai 21
Java Comparator interface

Java Comparator interface is used to order the objects of a user-defined class.

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


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

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

Methods of Java Comparator Interface


Method Description

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

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


obj) with the specified object.

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


obj) with the specified object.

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.

Java Comparator Example (Non-generic Old Style)

Let's see the example of sorting the elements of List on the basis of age and name. In
this example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java

This class contains three fields rollno, name and age and a parameterized
constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java

This class defines comparison logic based on the age. If the age of the first object is
greater than the second, we are returning a positive value. It can be anyone such as
1, 2, 10. If the age of the first object is less than the second object, we are returning a
negative value, it can be any negative value, and if the age of both objects is equal,
we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)

8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java

This class provides comparison logic based on the name. In such case, we are using
the compareTo() method of String class, which internally provides the comparison
logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }

Java 8 Comparator interface

Java 8 Comparator interface is a functional interface that contains only one abstract
method. Now, we can use the Comparator interface as the assignment target for a
lambda expression or method reference.

Difference between Comparable and


Comparator
Comparable and Comparator both are interfaces and can be used to sort collection
elements.

However, there are many differences between Comparable and Comparator


interfaces that are given below.
Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple


sequence. In other words, we can sort the sorting sequences. In other words,
collection on the basis of a single element we can sort the collection on the
such as id, name, and price. basis of multiple elements such as
id, name, and price etc.

2) Comparable affects the original class, Comparator doesn't affect the


i.e., the actual class is modified. original class, i.e., the actual class is
not modified.

3) Comparable provides compareTo() Comparator provides compare()


method to sort elements. method to sort elements.

4) Comparable is present A Comparator is present in


in java.lang package. the java.util package.

5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.

Properties class in Java

The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class
provides methods to get data from the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file

Recompilation is not required if the information is changed from a properties


file: If any information is changed from the properties file, you don't need to
recompile the java class. It is used to store information which is to be changed
frequently.
Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description

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

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

public void It is used to load all of the properties


loadFromXML(InputStream in) represented by the XML document on the
specified input stream into this properties
table.

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

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

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


String value)

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

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

public Enumeration<?> It returns an enumeration of all the keys


propertyNames()) from the property list.

public Set<String> It returns a set of keys in from property list


stringPropertyNames() where the key and its corresponding value
are strings.

public void store(Writer w, String It writes the properties in the writer object.
comment)

public void store(OutputStream os, It writes the properties in the OutputStream


String comment) object.

public void It writes the properties in the writer object


storeToXML(OutputStream os, String for generating XML document.
comment)
public void storeToXML(Writer w, It writes the properties in the writer object
String comment, String encoding) for generating XML document with the
specified encoding.

Example of Properties class to get information from the properties file

To get information from the properties file, create the properties file first.
db.properties
1. user=system
2. password=oracle

Now, let's create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle

Now if you change the value of the properties file, you don't need to recompile
the java class. That means no maintenance problem.

Difference between HashMap and Hashtable


HashMap and Hashtable both are used to store data in key and value form. Both are
using hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are
given below.
HashMap Hashtable

1) HashMap is non synchronized. It is not-thread Hashtable is synchronized. It is


safe and can't be shared between many threads thread-safe and can be shared
without proper synchronization code. with many threads.

2) HashMap allows one null key and multiple null Hashtable doesn't allow any
values. null key or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by Hashtable is internally


calling this code synchronized and can't be
Map m = Collections.synchronizedMap(hashMap); unsynchronized.

6) HashMap is traversed by Iterator. Hashtable is traversed by


Enumerator and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not


fail-fast.

8) HashMap inherits AbstractMap class. Hashtable


inherits Dictionary class.

Differences Between HashSet, LinkedHashSet, and TreeSet:

Features HashSet LinkedHashSet TreeSet

HashSet LinkedHashSet uses


Internal internally uses LinkedHashMap TreeSet uses TreeMap
Working HashMap for internally to store internally to store objects
storing objects objects
If you don’t If you want to
If you want to sort the
want to maintain maintain the insertion
When To elements according to
insertion order order of elements then
Use some Comparator then
but want to store you can use
use TreeSet
unique objects LinkedHashSet

While TreeSet orders the


elements according to
HashSet does LinkedHashSet
supplied Comparator. By
Order not maintain maintains the insertion
default, objects will be
insertion order order of objects
placed according to their
natural ascending order.

HashSet gives LinkedHashSet gives


While TreeSet gives the
O(1) complexity insertion, removing,
Complexity performance of order
for insertion, and retrieving
of O(log(n)) for insertion,
removing, and operations
Operations removing, and retrieving
retrieving performance in order
operations.
objects O(1).

The performance of
LinkedHashSet is
TreeSet performance is
slower than TreeSet. It
The performance better than
is almost similar to
of HashSet is LinkedHashSet except for
HashSet but slower
better when insertion and removal
Performance because
compared to operations because it has
LinkedHashSet
LinkedHashSet to sort the elements after
internally maintains
and TreeSet. each insertion and
LinkedList to maintain
removal operation.
the insertion order of
elements

HashSet uses
equals() and LinkedHashSet uses
TreeSet uses compare()
hashCode() equals() and
Compare and compareTo() methods
methods to hashCode() methods to
to compare the objects
compare the compare it’s objects
objects

Null LinkedHashSet allows TreeSet does not permit


HashSet allows
Elements only one null value. null value. If you insert
only one null
null value into TreeSet, it
value. will throw
NullPointerException.

HashSet obj = LinkedHashSet obj = TreeSet obj = new


Syntax
new HashSet(); new LinkedHashSet(); TreeSet();

You might also like