Professional Documents
Culture Documents
Collection Framework
Collection Framework
Collection Framework
Collection Framework
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of
objects.
No Method Description
.
11 Object getFirst()
Returns the first element in this list. Throws
NoSuchElementException if this list is empty.
12 Object getLast()
Returns the last element in this list. Throws
NoSuchElementException if this list is empty.
13 int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element,
or -1 if the list does not contain this element.
14 int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.
15 ListIterator listIterator(int index)
Returns a list-iterator of the elements in this list (in proper sequence),
starting at the specified position in the list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0
|| index >= size()).
16 Object remove(int index)
Removes the element at the specified position in this list. Throws
NoSuchElementException if this list is empty.
17 boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0
|| index >= size()).
18 Object removeFirst()
19 Object removeLast()
Removes and returns the last element from this list. Throws
NoSuchElementException if this list is empty.
20 Object set(int index, Object element)
Replaces the element at the specified position in this list with the
specified element. Throws IndexOutOfBoundsException if the specified
index is out of range (index < 0 || index >= size()).
21 int size()
Returns the number of elements in this list.
22 Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order. Throws NullPointerException if the specified array is null.
23 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct
order; the runtime type of the returned array is that of the specified
array.
Example
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[])
{ Output:
LinkedList<String> al=new
LinkedList<String>(); Rahul
al.add("Rahul"); Sameet
al.add(“Sameeth");
Sahira
al.add(“Sahira");
al.add("Aman"); Aman
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
import java.util.*; // remove first and last elements
public class LinkedListDemo { ll.removeFirst();
ll.removeLast();
public static void main(String args[]) { System.out.println("ll after deleting first
// create a linked list
and last: " + ll);
LinkedList ll = new LinkedList();
Class Description
Constructor Description
V putIfAbsent(K key, V It inserts the specified value with the specified key in the map only
value) if it is not already specified.
boolean remove(Object It removes the specified values with the associated specified keys
key, Object value) from the map.
V compute(K key, It is used to compute a mapping for the specified key and its
BiFunction<? super K,? current mapped value (or null if there is no current mapping).
super V,? extends V>
remappingFunction)
V computeIfAbsent(K key, It is used to compute its value using the given mapping function, if
Function<? super K,? the specified key is not already associated with a value (or is
extends V> mapped to null), and enters it into this map unless null.
mappingFunction)
V computeIfPresent(K It is used to compute a new mapping given the key and its current
key, BiFunction<? super mapped value if the value for the specified key is present and non-
K,? super V,? extends V> null.
remappingFunction)
boolean This method returns true if some value equal to the value exists
containsValue(Object within the map, else return false.
value)
boolean This method returns true if some key equal to the
containsKey(Object key) key exists within the map, else return false.
V get(Object key) This method returns the object that contains the
value associated with the key.
V merge(K key, V value, If the specified key is not already associated with a
BiFunction<? super V,? value or is associated with null, associates it with
super V,? extends V> the given non-null value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V It replaces the old value with the
oldValue, V newValue) new value for a specified key.
void replaceAll(BiFunction<? It replaces each entry's value with
super K,? super V,? extends V> the result of invoking the given
function) function on that entry until all
entries have been processed or
the function throws an exception.
Collection<V> values() It returns a collection view of the
values contained in the map.
int size() This method returns the number
of entries in the map.
Example -1
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();
//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} Iterating Hashmap...
} 1 Mango
} 2 Apple
3 Banana
4 Grapes
No Duplicate Key on HashMap- Example
import java.util.*;
public class HashMapExample2{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap< Iterating
Integer,String>();
Hashmap...
//Creating HashMap 1 Grapes
map.put(1,"Mango"); //Put elements in Map 2 Apple
map.put(2,"Apple"); 3 Banana
map.put(3,"Banana");
map.put(1,"Grapes"); //trying duplicate key
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue
());
}
}
}
import java.util.*;
class HashMap1{
public static void main(String args[]){ System.out.println("After invoking putI
HashMap<Integer,String> hm=new Has fAbsent() method ");
hMap<Integer,String>(); for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.
System.out.println("Initial list of eleme
getValue());
nts: "+hm);
}
hm.put(100,"Amit"); HashMap<Integer,String> map=new Has
hm.put(101,"Vijay"); hMap<Integer,String>();
hm.put(102,"Rahul"); map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll
System.out.println("After invoking pu
() method ");
t() method ");
for(Map.Entry m:map.entrySet()){
for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.
System.out.println(m.getKey()+" "+m getValue());
.getValue()); }
} }
hm.putIfAbsent(103, "Gaurav"); }
OUTPUT:
• 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.
Java TreeMap class
HashMap TreeMap
1) HashMap can contain one null TreeMap cannot contain any null
key. key.
2) HashMap maintains no order. TreeMap maintains ascending
order.
Java Hashtable class
• Java Hashtable class implements a hashtable, which maps
keys to values. It inherits Dictionary class and implements
the Map interface.
• Points to remember
• A Hashtable is an array of a list. Each list is known as a
bucket. The position of the bucket is identified by calling
the hashcode() method. A Hashtable contains values based
on the key.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or value.
• Java Hashtable class is synchronized.
• The initial default capacity of Hashtable class is 11 whereas
loadFactor is 0.75.
Java Hashtable Example: getOrDefault()
import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> map=new Has
htable<Integer,String>(); OUTPUT:
map.put(100,"Amit");
map.put(102,"Ravi"); Vijay
map.put(101,"Vijay"); Not Found
map.put(103,"Rahul");
//Here, we specify the if and else statem
ent as arguments of the method
System.out.println(map.getOrDefault(10
1, "Not Found"));
System.out.println(map.getOrDefault(10
5, "Not Found"));
}
}
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.
2) HashMap allows one null key and Hashtable doesn't allow any null
multiple null values. key or value.
3) HashMap is a new class Hashtable is a legacy class.
introduced in JDK 1.2.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as Hashtable is internally synchronized
synchronized by calling this code and can't be unsynchronized.
Map m =
Collections.synchronizedMap(hashMap
);
6) HashMap is traversed by Hashtable is traversed by
Iterator. Enumerator and Iterator.
7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-
fast.
8) HashMap Hashtable inherits Dictionary class.
inherits AbstractMap class.