UNIT 4 Part B
UNIT 4 Part B
UNIT 4 Part B
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.
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,
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.
4. get(K) - Returns the value associated with the specified key K. If the key is
not found, it returns null.
7. replace(K, V) - Replace the value of the key K with the new specified
value V.
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.
Here, the type of keys is String and the type of values is Integer.
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();
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.
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) {
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);
class Main {
public static void main(String[] args) {
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.
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);
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().
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
It's possible to create a linked hashmap without defining its capacity and load factor.
For example,
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
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
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);
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("New LinkedHashMap: " + numbers);
}
}
Run Code
Output
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
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) {
// 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
class Main {
public static void main(String[] args) {
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
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.
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.
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);
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("TreeMap of numbers: " + numbers);
}
}
Run Code
Output
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
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) {
// 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
Here, the getOrDefault() method does not find the key Five. Hence it returns the
specified default value 5.
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
// 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
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);
class Main {
public static void main(String[] args) {
// 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
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
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) {
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
}
@Override
public int compare(String number1, String number2) {
int value = number1.compareTo(number2);
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.
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.
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.
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
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
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, It compares the first object with the second
Object obj2) 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.
public void sort(List list, Comparator c): is used to sort the elements of List by the
given Comparator.
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 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.
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.
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.
Method Description
public void load(InputStream is) It loads data from the InputStream object
public String getProperty(String key, It searches for the property with the
String defaultValue) specified key.
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 void store(Writer w, String It writes the properties in the writer object.
comment)
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.
But there are many differences between HashMap and Hashtable classes that are
given below.
HashMap Hashtable
2) HashMap allows one null key and multiple null Hashtable doesn't allow any
values. null key or value.
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