TreeMap,LinkedHashMap,Iterator,ListIterator,Serialization
TreeMap,LinkedHashMap,Iterator,ListIterator,Serialization
A Sangeetha
Asst. Prof.
CSE Dept.
12-04-2025 CBIT
A Sangeetha, Asst. Prof. CSE Dept. CBIT 1
TreeMap
LinkedHashMap
Iterator
ListIterator
Serialization
•Benefits:
•Reduced Effort: It simplifies development by providing a standardized
way to work with collections, reducing the need to reinvent the wheel.
•Improved Performance: It enables efficient manipulation of collections,
leading to faster application execution.
•Interoperability: It promotes interoperability between different APIs by
providing a common way to represent and manipulate collections.
•Software Reuse: It fosters software reuse by providing reusable data
structures and algorithms.
•Benefits:
•Reduced Effort: It simplifies development by providing a standardized
way to work with collections, reducing the need to reinvent the wheel.
•Improved Performance: It enables efficient manipulation of collections,
leading to faster application execution.
•Interoperability: It promotes interoperability between different APIs by
providing a common way to represent and manipulate collections.
•Software Reuse: It fosters software reuse by providing reusable data
structures and algorithms.
Is a Balanced Tree
Properties of HashMap
1.Performance: If the hash function distributes the elements among the buckets
appropriately, HashMap offers constant-time performance for simple operations like put
and get.
2.Iteration: A hash map's entrySet(), keySet(), or values() methods are usually used to
iterate across the map and retrieve keys, values, or key-value pairs, respectively.
3.Resizing: The HashMap automatically resizes itself and rehashes the items to provide
optimal performance when the number of elements above a predetermined threshold.
12-04-2025
•Java TreeMap maintains ascending order.
A Sangeetha, Asst. Prof. CSE Dept. CBIT 11
TreeMap
Constructor and Description
1. TreeMap()Constructs a new, empty tree map, using the natural ordering of its keys.
2. TreeMap(Comparator<? super K> comparator)Constructs a new, empty tree map, ordered according to the given
comparator.
3. TreeMap(Map<? extends K,? extends V> m)Constructs a new tree map containing the same mappings as the given
map, ordered according to the natural ordering of its keys.
4. TreeMap(SortedMap<K,? extends V> m)Constructs a new tree map containing the same mappings and using the
same ordering as the specified sorted map.
Example1: TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
•remove(Object key)
•pollFirstEntry()
•pollLastEntry()
•clear()
// Output: [1, 3, 5, 7, 9]
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 19
TreeMap
View Operations
These methods return a subset or view of the map or keys.
•descendingKeySet()
•descendingMap()
TreeMap<Integer, String> map = new TreeMap< Integer, String >();
map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
•headMap(K toKey, boolean inclusive): Returns a view of the portion of this map whose keys are strictly
less than or equal toKey if inclusive value is true.
TreeMap<Integer, String> map = new TreeMap< Integer, String >();
map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
System.out.println("headMap(5): " + map.headMap(5));
// Output: {1=Apple, 3=Banana}
•tailMap(K fromKey):Returns a view of the portion of this map whose keys are greater than or equal
to fromKey.
•tailMap(K fromKey, boolean inclusive): Returns a view of the portion of this map whose keys are greater
than (or equal to, if inclusiveis true) fromKey.
•get(Object key) TreeMap<Integer, String> map = new TreeMap< Integer, String >();
•containsKey(Object key) map.put(1, "Apple");
•containsValue(Object value) map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
System.out.println("get(3): " + map.get(3)); // Output: Banana
•firstEntry(), firstKey() TreeMap<Integer, String> map = new TreeMap< Integer, String >();
•lastEntry(), lastKey() map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
System.out.println("firstEntry: " + map.firstEntry()); // Output: 1=Apple
System.out.println("firstKey: " + map.firstKey()); // Output: 1
•ceilingEntry(K key), ceilingKey(K key) TreeMap<Integer, String> map = new TreeMap< Integer, String >();
•floorEntry(K key), floorKey(K key) map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
•higherEntry(K key), higherKey(K key) TreeMap<Integer, String> map = new TreeMap< Integer, String >();
•lowerEntry(K key), lowerKey(K key) map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");
System.out.println("higherEntry(5): " + map.higherEntry(5)); // Output: 7=Date
System.out.println("higherKey(5): " + map.higherKey(5)); // Output: 7
LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer, String >(5, 0.75f, true);
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Access key 1 and 2
System.out.println(map.get(1));
System.out.println(map.get(2));
LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer, String >(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
return size() > 3; // remove oldest entry if more than 3 entries
}
};
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
map.put(4, "D"); // 1 is removed
System.out.println(map); // Output: {2=B, 3=C, 4=D}
putIfAbsent(K key, V value), putAll(Map<? extends K,? extends V> m), put(K key, V value)
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 40
LinkedHashMap
Map<Integer, String> map = Map.of(1, "Apple “, 2, "Banana", 3, "Cherry“,4, " Date ");
System.out.println(map.containsKey(2)); // true
System.out.println(map.containsKey(5)); // false
System.out.println(map.isEmpty()); // false
System.out.println(map.size()); // 4
map.remove(3); // Removes entry with key 3
System.out.println(map); // {1=Apple, 2=Banana, 4=Date}
map.remove(2, "Orange"); // Fails: wrong value
map.remove(2, "Banana"); // Succeeds
System.out.println(map); // {1=Apple, 4=Date}
map.replace(1, "Apricot");
System.out.println(map); // {1=Apricot, 4=Date}
map.replace(4, "Date", "Dragonfruit");
System.out.println(map); // {1=Apricot, 4=Dragonfruit}
remove(Object key), remove(Object key, Object value), replace(K key, V value), replace(K key, V oldValue, V newValue)
containsKey(Object key), isEmpty(), size()
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 41
LinkedHashMap
From the previous slide map is having two key-value pairs ie {1=Apricot, 4=Dragonfruit}
// compute(K key, BiFunction)
map.compute(1, (k, v) -> v + " Pie");
System.out.println(map); // {1=Apricot Pie, 4=Dragonfruit}
Uses
•Traverse and read collection elements
•Safely remove elements during iteration (avoids ConcurrentModificationException)
Method Description
boolean hasNext() Returns true if the iteration has more elements.
E next() Returns the next element in the iteration.
void remove() Removes the current element from the underlying collection.
Method Description
boolean hasNext() Returns true if there is a next element.
E next() Returns the next element.
boolean hasPrevious() Returns true if there is a previous element.
E previous() Returns the previous element.
int nextIndex() Returns the index of the next element.
int previousIndex() Returns the index of the previous element.
void add(E e) Inserts the element into the list at the current position.
void set(E e)
12-04-2025
Replaces the last element returned with the specified element.
A Sangeetha, Asst. Prof. CSE Dept. CBIT 44
Difference: Iterator vs ListIterator
while (itr.hasNext()) {
String element = itr.next();
if (element.equals("Two")) {
itr.set("Two Modified"); // Replace "Two"
itr.add("Two and Half"); // Add after "Two Modified"
}
}
System.out.println("Modified List: " + list);
//output: Modified List: [One, Two Modified, Two and Half, Three]
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 47
Serialization and Deserialization
Serialization Formats
Various formats can be used for serialization, including:
•JSON: A human-readable text format that's easy to parse and widely used in web applications.
•XML: Another text-based format that's both human- and machine-readable, often used in configuration files and
data interchange.
•Binary: A compact format that's efficient for storage and transmission but not human-readable.
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 49
The choice of format depends on factors like readability, performance, and interoperability requirements.
Serialization and Deserialization
Applications
Serialization and deserialization are widely used in various applications
•Distributed Systems: Transmitting objects between different machines.
•Web Applications: Sending objects between a web server and a browser.
•Data Storage: Saving object states in databases for later retrieval
Step 1. Deserialize the Object use ObjectInputStream class and readObject method
When you mark a field as transient, it tells the Java serialization mechanism not to include that field in the
serialized representation of the object. This is useful when:
•The field is sensitive (e.g., passwords).
•The field is not serializable.
•The field can be recomputed or is not critical to persist.
import java.io.*;
// Serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"));
out.writeObject(user);
out.close();
// Deserialize
ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"));
User deserializedUser = (User) in.readObject();
in.close();