0% found this document useful (0 votes)
1 views

TreeMap,LinkedHashMap,Iterator,ListIterator,Serialization

The document outlines a short-term training program on upgrading skills in Java programming, focusing on the Java Collections Framework, including HashMap and TreeMap. It details the benefits, properties, and operations of these data structures, emphasizing their roles in efficient data manipulation and storage. The program is scheduled for several dates in March and April 2025, led by A Sangeetha from the CSE Department at CBIT.

Uploaded by

brecwcseb 20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

TreeMap,LinkedHashMap,Iterator,ListIterator,Serialization

The document outlines a short-term training program on upgrading skills in Java programming, focusing on the Java Collections Framework, including HashMap and TreeMap. It details the benefits, properties, and operations of these data structures, emphasizing their roles in efficient data manipulation and storage. The program is scheduled for several dates in March and April 2025, led by A Sangeetha from the CSE Department at CBIT.

Uploaded by

brecwcseb 20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Short Term Training Program

(Value added Course)


on
Upgrading Skills in Java Programming
(15th, 22nd, 29th March, 2025, 12th April,
2025, and 13th April, 2025)

A Sangeetha
Asst. Prof.
CSE Dept.
12-04-2025 CBIT
A Sangeetha, Asst. Prof. CSE Dept. CBIT 1
TreeMap
LinkedHashMap
Iterator
ListIterator
Serialization

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 2


Java Collections Framework
The Java Collections Framework is a unified architecture that provides
interfaces and classes for representing and manipulating collections,
enabling developers to work with groups of objects efficiently and
independently of their underlying implementation.
•Unified Architecture:
It provides a standardized way to represent and manipulate collections,
making it easier to work with different data structures.
•Interfaces and Classes:
The framework consists of interfaces (like Collection, List, Set, and Map) that
define the behavior of collections, and classes
(like ArrayList, LinkedList, HashSet, and HashMap) that implement those
interfaces.
Java Collections Framework

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

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 4


Java Collections Framework

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

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 5


Hash Table +
Linked List
Hash Table

Is a Balanced Tree

Source of this image : https://medium.com/@mbanaee61/mastering-the-java-collections-framework-hierarchy-with-java-code-and-junit-testing-ab2eb87746ed

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 6


Java Collections Framework
HashMap
• Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be
unique.
• If you try to insert the duplicate key, it will replace the element of the corresponding key.
• It is easy to perform operations using the key index like updation, deletion, etc.
• HashMap class is found in the java.util package.
• HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
• It allows us to store the null elements as well, but there should be only one null key.

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 A Sangeetha, Asst. Prof. CSE Dept. CBIT 7


HashMap
Properties of HashMap
4. Load Factor: The load factor that you can set in a hash map tells you when the map should resize in
relation to its capacity. The load factor by default is 0.75.
5. Collision Handling: When two distinct keys have the same hash, a hash collision is handled by HashMap
using distinct chaining to store multiple entries in the same bucket and preserve a linked list of entries.
6. Fail-Fast Iterator: When you get an iterator from a HashMap (for example, using
map.keySet().iterator()), that iterator is considered fail-fast. If you modify the structure of the HashMap
after creating the iterator — such as by adding or removing entries (e.g., map.put(...) or map.remove(...)) —
the iterator will detect this change.
•When such a structural change is detected, the iterator will throw a ConcurrentModificationException.
•The only safe way to remove elements while using the iterator is by calling the iterator.remove() method —
not by modifying the map directly.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT


https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html 8
HashMap
Points to Remember
• Java HashMap contains values based on the key.
• Java HashMap contains only unique keys.
• Java HashMap may have one null key and multiple null values.
• Java HashMap is non synchronized.
• Java HashMap maintains no order.
• The initial default capacity of Java HashMap class is 16 with a load
factor of 0.75.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 9


TreeMap
• Java TreeMap class is a red-black tree-based implementation. It provides an efficient
means of storing key-value pairs in sorted order.
• The java.util package contains the Java TreeMap class, which is a component of the
Java Collections Framework.
• It extends the AbstractMap class and implements the NavigableMap interface.
• TreeMap is an effective red-black tree-based solution that sorts key-value pairs.
• TreeMap works well in situations where ordered key-value pairs are necessary since it
preserves ascending order.
• It also only includes distinct components, guaranteeing that every key corresponds to a
single value.
• TreeMap can have more than one null value, even if it cannot have a null key.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 10


TreeMap
The important points about Java TreeMap class are:

•Java TreeMap contains values based on the key. It


implements the NavigableMap interface and extends
AbstractMap class.

•Java TreeMap contains only unique elements.

•Java TreeMap cannot have a null key but can have


multiple null values.

•Java TreeMap is non synchronized.

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>();

Example2 : Comparator<Integer> reverseOrder = Comparator.reverseOrder();


TreeMap<Integer,String> tm1=new TreeMap<Integer,String>(reverseOrder);

Example3 :TreeMap<Integer,String> tm2=new TreeMap<Integer,String>(tm);

Example4 : HashMap<Integer,String> hm=new HashMap<Integer,String>();


hm.put(10,"hello"); hm.put(20,"ABC"); hm.put(-10,"XYZ");
TreeMap<Integer,String> tm3=new TreeMap<Integer,String>(hm);

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 12


TreeMap
Update Operations
These modify the contents of the map.

•put(K key, V value)


•putAll(Map<? extends K,? extends V> map)

•replace(K key, V value)


•replace(K key, V oldValue, V newValue)
•replaceAll(BiFunction<? super K,? super V,? extends V> function)

•remove(Object key)
•pollFirstEntry()
•pollLastEntry()
•clear()

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 13


TreeMap
Update Operations
These modify the contents of the map.

•put(K key, V value)


TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");

•putAll(Map<? extends K,? extends V> map)


HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(10,"hello");
hm.put(20,"ABC");
hm.put(-10,"XYZ");
TreeMap<Integer,String> tm3=new TreeMap<Integer,String>();
tm3.putAll(hm);
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 14
TreeMap
Update Operations
These modify the contents of the map.
•replace(K key, V value)
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");
tm.replace(1, "sam");
•replace(K key, V oldValue, V newValue)
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");
tm.replace(1, "Joe","James");
•replaceAll(BiFunction<? super K,? super V,? extends V> function)
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 15
tm.replaceAll((k,v)->v.toUpperCase());
TreeMap
Update Operations
These modify the contents of the map.
•remove(Object key)
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");
tm.remove(3);
tm.remove(3,"John"); //removes only if value matches for the given key
•pollFirstEntry()
•pollLastEntry()
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(3,"John");
tm.put(1,"Joe");
•clear(): removesall
tm.put(4,"James");
System.out.println(tm.pollFirstEntry()); // removes and returns 1=Joe
System.out.println(tm.pollLastEntry()); // removes and return 4=James
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 16
TreeMap
View Operations
These methods return a subset or view of the map or keys.
•keySet()
•values() TreeMap<Integer, String> map = new TreeMap< Integer, String >();
map.put(1, "Apple");
•entrySet()
map.put(3, "Banana");
•navigableKeySet() map.put(5, "Cherry");
•descendingKeySet() map.put(7, "Date");
•descendingMap() map.put(9, "Elderberry");
•headMap(K toKey)
•headMap(K toKey, boolean inclusive)
•tailMap(K fromKey)
•tailMap(K fromKey, boolean inclusive)
•subMap(K fromKey, K toKey)
•subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 17


TreeMap
View Operations
These methods return a subset or view of the map or keys.
•keySet()
•values()

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("keySet: " + map.keySet());


// Output: [1, 3, 5, 7, 9]

System.out.println("values: " + map.values());


// Output: [Apple, Banana, Cherry, Date, Elderberry]

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 18


TreeMap
View Operations
These methods return a subset or view of the map or keys.
•entrySet()
•navigableKeySet()

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("entrySet: " + map.entrySet());

// Output: [1=Apple, 3=Banana, 5=Cherry, 7=Date, 9=Elderberry]

System.out.println("navigableKeySet: " + map.navigableKeySet());

// 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");

System.out.println("descendingKeySet: " + map.descendingKeySet());


// Output: [9, 7, 5, 3, 1]

System.out.println("descendingMap: " + map.descendingMap());


// Output: {9=Elderberry, 7=Date, 5=Cherry, 3=Banana, 1=Apple}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 20


TreeMap
View Operations
These methods return a subset or view of the map or keys.
•headMap(K toKey): Returns a view of the portion of this map whose keys are strictly less than toKey.

•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}

System.out.println("headMap(5, true): " + map.headMap(5, true));


// Output: {1=Apple, 3=Banana, 5=Cherry}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 21


TreeMap
View Operations
These methods return a subset or view of the map or keys.

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

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("tailMap(5): " + map.tailMap(5));
// Output: {5=Cherry, 7=Date, 9=Elderberry}

System.out.println("tailMap(5, false): " + map.tailMap(5, false));


// Output: {7=Date, 9=Elderberry}
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 22
TreeMap
View Operations
These methods return a subset or view of the map or keys.
•subMap(K fromKey, K toKey)
•subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)

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("subMap(3, 7): " + map.subMap(3, 7));
// Output: {3=Banana, 5=Cherry}

System.out.println("subMap(3, true, 7, true): " + map.subMap(3, true, 7, true));


// Output: {3=Banana, 5=Cherry, 7=Date}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 23


TreeMap
Query & Retrieval Operations
These methods retrieve values, keys, or entries without modifying the map.

•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

System.out.println("containsKey(5): " + map.containsKey(5)); // Output: true

System.out.println("containsValue(\"Cherry\"): " + map.containsValue("Cherry")); // Output: true

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 24


TreeMap
Query & Retrieval Operations
These methods retrieve values, keys, or entries without modifying the map.

•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

System.out.println("lastEntry: " + map.lastEntry()); // Output: 9=Elderberry


System.out.println("lastKey: " + map.lastKey()); // Output: 9

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 25


TreeMap
Query & Retrieval Operations
These methods retrieve values, keys, or entries without modifying the map.

•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");

System.out.println("ceilingEntry(4): " + map.ceilingEntry(4)); // Output: 5=Cherry


System.out.println("ceilingKey(4): " + map.ceilingKey(4)); // Output: 5

System.out.println("floorEntry(6): " + map.floorEntry(6)); // Output: 5=Cherry


System.out.println("floorKey(6): " + map.floorKey(6)); // Output: 5

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 26


TreeMap
Query & Retrieval Operations
These methods retrieve values, keys, or entries without modifying the map.

•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

System.out.println("lowerEntry(5): " + map.lowerEntry(5)); // Output: 3=Banana


System.out.println("lowerKey(5): " + map.lowerKey(5)); // Output: 3

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 27


TreeMap
Query & Retrieval Operations
These methods retrieve values, keys, or entries without modifying the map.

•size() TreeMap<Integer, String> map = new TreeMap< Integer, String >();


•comparator() map.put(1, "Apple");
map.put(3, "Banana");
map.put(5, "Cherry");
map.put(7, "Date");
map.put(9, "Elderberry");

System.out.println("size: " + map.size()); // Output: 5

System.out.println("comparator: " + map.comparator()); // Output: null (means natural ordering is used)

Comparator<Integer> reverseOrder = Comparator.reverseOrder();


TreeMap<Integer,String> tm1=new TreeMap<Integer,String>(reverseOrder);
System.out.println("comparator: " + map.comparator());
//output: java.util.Collections$ReverseComparator@7a81197d
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 28
TreeMap
Iteration and Processing
Used for looping or processing entries.
•forEach(BiConsumer<? super K,? super V> action)
TreeMap<Integer, String> map = new TreeMap< Integer, String >();
map.put(1, "Apple"); Output:
map.put(2, "Banana"); Key: 1, Value: Apple
map.put(3, "Cherry"); Key: 2, Value: Banana
Key: 3, Value: Cherry
// Using forEach to print all key-value pairs
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});

Utility Methods TreeMap<Integer, String> clonedMap = (TreeMap<Integer,


Special-purpose or support features. String>) map.clone();
•clone()
// Print both maps
System.out.println("Original TreeMap: " + map);
System.out.println("Cloned TreeMap: " + clonedMap);
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 29
LinkedHashMap
• Java LinkedHashMap class is Hashtable and Linked list
implementation of the Map interface, with predictable iteration
order. It inherits HashMap class and implements the Map interface.
• Points to remember
• Java LinkedHashMap contains values based on the key.
• Java LinkedHashMap contains unique elements.
• Java LinkedHashMap may have one null key and multiple null values.
• Java LinkedHashMap is non synchronized.
• Java LinkedHashMap maintains insertion order.
• The initial default capacity of Java HashMap class is 16 with a load
factor of 0.75.
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 30
LinkedHashMap
LinkedHashMap()Constructs an empty insertion-ordered LinkedHashMap instance with the default initial
capacity (16) and load factor (0.75).

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


map.put(1, "Apple");
map.put(2, "Banana");

LinkedHashMap(int initialCapacity)Constructs an empty insertion-ordered LinkedHashMap instance with the


specified initial capacity and a default load factor (0.75).

LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer, String >(10);


map.put(1, "Cat");
map.put(2, "Dog");

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 31


LinkedHashMap
LinkedHashMap(int initialCapacity, float loadFactor)Constructs an empty insertion-
ordered LinkedHashMap instance with the specified initial capacity and load factor.

LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer, String >(5, 0.6f);


map.put(1, "Red");
map.put(2, "Blue");
System.out.println(map);

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 32


LinkedHashMap
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)Constructs an
empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.

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));

System.out.println(map); // Order will change: 3 → 1 → 2

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 33


LinkedHashMap
LinkedHashMap(Map<? extends K,? extends V> m)Constructs an insertion-ordered LinkedHashMap instance
with the same mappings as the specified map.

Map<Integer, String> original = new HashMap< Integer, String >();


original.put(3, "Three");
original.put(1, "One");
original.put(2, "Two");

LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer, String >(original);


System.out.println(map);

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 34


LinkedHashMap
Category Methods
Modification clear(), replaceAll(), removeEldestEntry()
Query/Retrieval get(), getOrDefault(), containsValue()
View entrySet(), keySet(), values()
Traversal forEach()

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


map.put(1, "Apple"); map.put(2, "Banana");
map.clear(); // All entries are removed
System.out.println(map); // Output: {}

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


map.put(1, "apple"); map.put(2, "banana");
map.replaceAll((k, v) -> v.toUpperCase());
System.out.println(map); // Output: {1=APPLE, 2=BANANA}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 35


LinkedHashMap
Category Methods
Modification clear(), replaceAll(), removeEldestEntry()
Query/Retrieval get(), getOrDefault(), containsValue()
View entrySet(), keySet(), values()
Traversal forEach()

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}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 36


LinkedHashMap
Category Methods
Modification clear(), replaceAll(), removeEldestEntry()
Query/Retrieval get(), getOrDefault(), containsValue()
View entrySet(), keySet(), values()
Traversal forEach()

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


map.put("Math", 85);
System.out.println(map.get("Math")); // Output: 85

System.out.println(map.getOrDefault("Science", 0)); // Output: 0

System.out.println(map.containsValue(85)); // Output: true


System.out.println(map.containsValue(100)); // Output: false

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 37


LinkedHashMap
Category Methods
Modification clear(), replaceAll(), removeEldestEntry()
Query/Retrieval get(), getOrDefault(), containsValue()
View entrySet(), keySet(), values()
Traversal forEach()

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


map.put("Math", 85);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
} // output: Math=85

Set<String> keys = map.keySet();


System.out.println(keys); // Output: [Math]

Collection<Integer> values = map.values();


System.out.println(values); // Output: [85]
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 38
LinkedHashMap
Category Methods
Modification clear(), replaceAll(), removeEldestEntry()
Query/Retrieval get(), getOrDefault(), containsValue()
View entrySet(), keySet(), values()
Traversal forEach()

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


map.put("Math", 85);

map.forEach((k, v) -> System.out.println(k + " -> " + v));

// Output: Math -> 85

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 39


LinkedHashMap

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


map.put(1, "Apple");
System.out.println(map); // {1=Apple}

Map<Integer, String> anotherMap = Map.of(2, "Banana", 3, "Cherry");


map.putAll(anotherMap);
System.out.println(map); // {1=Apple, 2=Banana, 3=Cherry}

map.putIfAbsent(2, "Blueberry"); // Won't overwrite existing value


map.putIfAbsent(4, "Date"); // Will insert
System.out.println(map); // {1=Apple, 2=Banana, 3=Cherry, 4=Date}

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}

// computeIfAbsent(K key, Function)


map.computeIfAbsent(5, k -> "Elderberry");
System.out.println(map); // {1=Apricot Pie, 4=Dragonfruit, 5=Elderberry}

// computeIfPresent(K key, BiFunction)


map.computeIfPresent(4, (k, v) -> v.toUpperCase());
System.out.println(map); // {1=Apricot Pie, 4=DRAGONFRUIT, 5=Elderberry}

// merge(K key, V value, BiFunction)


map.merge(5, " Jam", (oldVal, newVal) -> oldVal + newVal);
System.out.println(map); // {1=Apricot Pie, 4=DRAGONFRUIT, 5=Elderberry Jam}
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 42
Iterator
Iterator is an interface in Java (in java.util package) used to traverse elements of a Collection (like
List, Set, Map views) sequentially, one element at a time.

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.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 43


ListIterator
ListIterator is an interface that extends Iterator. It is specifically designed for lists and allows bi-directional
traversal (forward and backward).
Uses
•Traverse list forward and backward
•Modify list (add, set, remove elements) during iteration
•Used only for List classes ie ArrayList, LinkedList

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 remove() Removes the last element returned by next() or previous().

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

Feature Iterator ListIterator


Applicable to All Collections Only Lists
Forward and
Direction Forward only
Backward
Can add, remove,
Can modify list Can remove
replace
Knows current index No Yes
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 45
Iterator and ListIterator Example on ArrayList Class
ArrayList<String> fruits = new ArrayList<>();
ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple");
fruits.add("Apple"); fruits.add("Banana");
fruits.add("Banana"); fruits.add("Cherry");
fruits.add("Cherry");
Iterator<String> iterator = fruits.iterator(); ListIterator<String> iterator = fruits.listIterator();
System.out.println("Iterating using Iterator:");
while (iterator.hasNext()) { System.out.println("Forward Iteration:");
String fruit = iterator.next(); while (iterator.hasNext()) {
System.out.println(fruit); System.out.println(iterator.next();
}
//Output: Apple System.out.println("\nBackward Iteration:");
Banana while (iterator.hasPrevious()) {
Cherry System.out.println(iterator.previous());
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 46
}
Example Using ListIterator to Modify ArrayList
ArrayList<String> list = new ArrayList<>(Arrays.asList("One", "Two", "Three"));
ListIterator<String> itr = list.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 is the process of converting an object's state into a


byte stream. This byte stream can then be saved to a file, sent over
a network, or stored in a database. The primary goal is to preserve
the object's state so that it can be recreated later.

• Deserialization is the reverse process of serialization. It involves


converting a byte stream back into a copy of the original object.
This is essential for reconstructing objects after they've been
transmitted or stored.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 48


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

Considerations and Drawbacks


While serialization and deserialization are powerful, they come with certain considerations:
•Performance: The process can be computationally intensive, especially for large or complex objects.
•Platform and Language Dependencies: Different programming languages and platforms may have their
own serialization mechanisms, leading to compatibility issues.
•Versioning: Changes in the structure of serialized objects over time can lead to deserialization problems if
not managed properly.

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 50


Serialization and Deserialization
In Java, serialization and deserialization are commonly achieved using the Serializable interface, along
with classes like ObjectOutputStream and ObjectInputStream.

Step-by-Step: Serialization in Java

Step 1. Implement Serializable to a class who objects need to be serialize


Step2 . Serialize the Object using ObjectOutputStream class and writeObject method

Step-by-Step: Deserialization in Java

Step 1. Deserialize the Object use ObjectInputStream class and readObject method

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 51


Serialization and Deserialization
Step-by-Step: Serialization in Java

Step 1. Implement Serializable to a class who objects need to be serialize


Step2 . Serialize the Object using ObjectOutputStream class
import java.io.*;
import java.io.Serializable;
public class SerializeExample {
public class Student implements Serializable { public static void main(String[] args) {
String name; Student s1 = new Student("Alice", 21);
int age;
try (ObjectOutputStream out = new ObjectOutputStream(new
public Student(String name, int age) { FileOutputStream("student.ser"))) {
this.name = name; out.writeObject(s1);
this.age = age; System.out.println("Object serialized successfully.");
} } catch (IOException e) {
} e.printStackTrace();
}
}
12-04-2025
}
A Sangeetha, Asst. Prof. CSE Dept. CBIT 52
Serialization and Deserialization
Step-by-Step: Deserialization in Java

Step 1. Deserialize the Object use ObjectInputStream class

import java.io.Serializable; import java.io.*;

public class Student implements Serializable { public class DeserializeExample {


String name; public static void main(String[] args) {
int age; try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream("student.ser"))) {
public Student(String name, int age) { Student s2 = (Student) in.readObject();
this.name = name; System.out.println("Deserialized Student: " + s2.name + ",
this.age = age; Age: " + s2.age);
} } catch (IOException | ClassNotFoundException e) {
} e.printStackTrace();
}
}
}

12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 53


Serialization and Deserialization
What is transient?

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.*;

class User implements Serializable {


String username;
transient String password; // won't be saved

public User(String username, String password) {


this.username = username;
this.password = password;
}
}
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 54
Serialization and Deserialization
What is transient?

public class TransientDemo {


public static void main(String[] args) throws Exception {
User user = new User("john_doe", "secret123");

// 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();

System.out.println("Username: " + deserializedUser.username); // john_doe


System.out.println("Password: " + deserializedUser.password); // null
}
12-04-2025 A Sangeetha, Asst. Prof. CSE Dept. CBIT 55
}

You might also like