Collection Framework
Collection Framework
********************
Arrays:
store the group of objects : homogenous
arrays are fixed in size : we can not increase & decarese the size
memory : int[] 100 : memory wise bad
Arrays are no methods : operations are complex
Arrays can store primitive int[] it can store object data Emp[]
Collections:
store the gruop of objects : homgenous & hetrogenous
Colelctions are growable in nature : size will increase & decarase
memory wise it is good
collections support methods operations are esay.
collections can store only object data.
Definitions of Collection:
a. The main objective of collections framework is to represent group of objects as
a single entity.
b. java Collection framework provide very good architecture to store and manipulate
the group of objects.
c. Collection contains group of classes and interfaces that makes it easier to
handle group of objects.
b. Map : used to store the data two objects format in the form of key:value
{111:"ratan",222:"anu"}
Map implementation classes : HashMap , LinkedHashMap , TreeMap ,
Hashtable
Iterable(i) 1.5 v
|
Collection(i) 1.2 v
|
List(i)1.2v
|
ArrayList(c) LinkedList(c) Vector(c) 1.0 v
1.2 v 1.2v |
Stack(c) 1.0 v
ArrayList : 1.2
1. ArrayList Duplicate objects are allowed
2. ArrayList ordered colection.
3. ArrayList allows null is allowed.
4. ArrayList methods are non-synchronized.
5. ArrayList uderlaying data structure is Resizable-array.
ArrayList Constructors:
1. ArrayList()
ArrayList objs = new ArrayList();
Constructs an empty list with an initial capacity of ten.
once it will reach max capacity the new capacity
new capacity = old capacity * 3/2+1
2. ArrayList(int initialCapacity)
ArrayList objs = new ArrayList(20);
Constructs an empty list with the specified initial capacity.
primitive data types : byte, short, int, long, float, double, char, boolean
wrapper calsses : Byte, Short, Integer, Long, Float, Double, Character,
Boolean
ex-1:
package com.tcs;
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) {
ArrayList objs = new ArrayList();
objs.add(10);
objs.add("ratan");
objs.add(10);
objs.add(null);
objs.add(10.5);
System.out.println(objs);
}
}
//Student.java
package com.tcs;
public class Student {
Integer sid;
String sname;
public Student(int sid, String sname) {
super();
this.sid = sid;
this.sname = sname;
}
}
//ArrayListEx2.java
package com.tcs;
import java.util.ArrayList;
Student s = (Student)objs.get(1);
System.out.println(s.sid+" "+s.sname);
}
}
Collections are not type safe (no guarantee on data) it means the collections can
store different types of objects.
ArrayList al = new ArrayList();
al.add(new Emp(111,"ratan"));
al.add(new Student(222,"anu"));
If the collections are not type safe then while reading the data at runtime we have
to perform
Type casting process, but it is not recommanded.
To overcome above problems to provide the type safety to the collections use
generics.
Note : Arrays are used to store the homogeneous data & collections generic version
also used to store homogeneous data but collections provides more flexibility with
respect to the memory & operations.
scanner.close();
}
}
import java.util.ArrayList;
System.out.println(al.size()); // 6
System.out.println(al);
al.remove(2);
al.remove("ratan");
System.out.println(al); // 10 10.5 anu 10 null
al.set(1, "rani");
System.out.println(al); // 10 rani anu 10 null
System.out.println(al.isEmpty()); //false
al.clear();
System.out.println(al.isEmpty()); // true
}
}
Note: If we want to insert or remove the data frequently then Arraylist is not
recommanded. Because it will take more shift operations.
Observation:
package com.tcs;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(10.5);
al.add("ratan");
al.remove("ratan");
al.remove(10); // java.lang.IndexOutOfBoundsException: Index: 10,
Size: 2
System.out.println(al);
}
}
ex 5: Basic Operations
Collection vs. Collections
Collection is a root interface of collection framework.
whereas Collections is class it contains some methods to perform operations.
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
ex-1:
There are two ways to add one collection data into another collection.
i. By using constructor approach. : one to one [a1 is added in
a2]
ii. By using addAll() method. : many to one [b1,b2 is
added in b3]
package com.tcs;
import java.util.ArrayList;
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
a2.remove(e1);
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
for(Emp e : a2)
{ System.out.println(e.eid+" "+e.ename);
}
}
}
package com.tcs;
import java.util.ArrayList;
for(Emp e : a2)
{ System.out.println(e.eid+" "+e.ename);
}
removeAll() : Removes from this list all of its elements that are contained in the
specified collection.
retainAll() : Retains only the elements in this list that are contained in thes
pecified collection. In other words, removes from this list
all of its elements that are not contained in the
specified collection.
ex: Assignmne
public class Book {
int id;
String bname;
double price;
public Book(int id, String bname, double price) {
super();
this.id = id;
this.bname = bname;
this.price = price;
}
}
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Book> allBooks =
new ArrayList<Book>(Collections.nCopies(3, new Book(333,
"springboot", 600.45)));
allBooks.addAll(tech);
allBooks.addAll(nontech);
System.out.println(allBooks.containsAll(nontech));
System.out.println(allBooks.containsAll(tech));
Book b = allBooks.get(2);
System.out.println(b.id + " " + b.bname + " " + b.price);
for(Book bb : allBooks) {
System.out.println(bb.id + " " + bb.bname + " " + bb.price);
}
}
}
package com.tcs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
class Test
{ public static void main(String[] args)
{ List<String> data = List.of("ratan","anu","sravya");
System.out.println(data);
As of the Java 2 platform v1.2, this class was retrofitted to implement the
List interface, making it a member of the Java Collections Framework. Unlike the
new collection implementations, Vector is synchronized so it is thread-safe. If a
thread-safe implementation is not needed, it is recommended to use ArrayList in
place of Vector.
Vector Constructor:
Vector()
Constructs an empty vector so that its internal data array has size 10 and
its standard capacity increment is zero.
Vector(int initialCapacity)
Constructs an empty vector with the specified initial capacity once it
reaches maximum capacity the capacity becomes double.
import java.util.ArrayList;
import java.util.Vector;
System.out.println("********");
System.out.println("********");
System.out.println("********");
ArrayList<String> al = new ArrayList<String>();
al.add("anu");
Vector<String> v = new Vector<String>(al);
v.add("ratan");
System.out.println(v);
}
}
Note:
Arrays are performance good
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11 12 13 14
once we create the Vector with size 10, once it reaches maximum capacity then the
new Vector memory space created with new capacity.After that old data is copied to
new memory. The old data is garbage collected.
LinkedList(java 1.2):
1. Duplicates are allowed.
2. Insertion order is preserved.
3. null is always allowed.
4. Methods are non-sync.
5. Doubly-linked list implementation of the List and Deque interfaces.
constructors:
LinkedList()
Constructs an empty list.
LinkedList(Collection<? extends E> c)
Adding one collections data into another collection.
l.removeFirst();
l.removeLast();
System.out.println("after deletion first & last:-"+l);
l.remove("E");
l.remove(2);
System.out.println("after deletion :-"+l);
l.set(2,"ratan");
System.out.println("after seting:-"+l);
System.out.println(l.isEmpty());
l.clear();
System.out.println(l.isEmpty());
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("ram");
2. when we are doing Insertion, remove data on Arraylist is slow because when we
perform these operations internally it requires more shift
operations.
But insertion,remove operations LinkedList is faster because shift
operations are not required. Just adding or removing one link.
However, unlike arrays which allow random access to the elements contained
within them, a link list only allows sequential access to its elements.
Stack: java1.0
The Stack class represents a last-in-first-out (LIFO)
It extends class Vector
constructors :
Stack(): Creates an empty Stack.
package com.tcs;
import java.util.Stack;
public class StackEx {
public static void main(String[] args) {
Stack<String> s = new Stack<String>();
s.push("ratan");
s.push("anu");
s.push("naresh");
s.push("sravya");
System.out.println(s);
System.out.println(s.size());
s.pop();
System.out.println(s);
System.out.println(s.search("naresh"));
System.out.println(s.peek());
System.out.println(s.empty());
s.clear();
System.out.println(s.empty());
}
}
naresh 1
anu 2
ratan 3
Note2:
ArrayList al = new ArrayList(); // valid but not recommanded
ArrayList al = sahilaja.getObjects();
innitially shilaja returns ArrayList object then above code will work.
later silaja changed return type to LinkedList then above code will not
work.
List al = sahilaja.getObjects();
innitially shilaja returns ArrayList object then above code will work.
later silaja changed return type to LinkedList then above code will
work.
ex-4:
import java.util.*;
class Test
{
public static void m1(ArrayList<String> objs)
{ for (String str : objs)
{ System.out.println(str);
}
}
System.out.println("*********");
Test.m2(l);
}
}
ex-5:
package com.tcs;
import java.util.ArrayList;
import java.util.List;
class Ramya
{ public static ArrayList<String> getObjects()
{ ArrayList<String> data = new ArrayList<String>();
data.add("ratan");
data.add("anu");
data.add("sravya");
return data;
}
}
public class ArrayListEx7 {
public static void main(String[] args) {
package com.tcs.listexamples;
import java.util.ArrayList;
import java.util.List;
}
}
boolean hasMoreElements()
Tests if this enumeration contains more elements.
true if and only if this enumeration object contains at least one
more element to provide; false otherwise.
E nextElement()
Returns the next element of this enumeration if this enumeration
object has at least one more element to provide.
ex-1:
package com.tcs.cursors;
import java.util.ArrayList;
import java.util.Iterator;
System.out.println("***Get() method****");
String name = objs.get(2);
System.out.println(name);
@FunctionalInterface
public interface Consumer<T>{
void accept(T t)
}
Note:
a. If the method is excepting the functional interface, so the functional interface
contains only one method then write that method implementation using lambda
expression.
b. Method reference is a short form of lambda expression. In method reference the
variable name decides internally.
ex-2: Iterator to remove the data.
package com.tcs;
import java.util.ArrayList;
import java.util.Iterator;
ex-3:
package com.tcs.cursors;
import java.util.ArrayList;
import java.util.ListIterator;
public class Test2 {
public static void main(String[] args) {
ArrayList<String> objs = new ArrayList<String>();
objs.add("ratan");
objs.add("anu");
objs.add("naresh");
objs.add("sravya");
while(glistitr.hasNext())
{ String s = glistitr.next();
if(s.equals("anu"))
glistitr.set("anushka");
if(s.equals("naresh"))
glistitr.remove();
}
System.out.println(objs); // lipika ratan anushka sravya
}
}
When we create the cursor object, cursor is pointing to before first record.So when
we add the data using cursor the data is added at frist location.
ratan
anu
naresh
System.out.println("*******");
while(lstr.hasPrevious())
{ String str = lstr.previous();
System.out.println(str);
}
}
}
ex:
package com.tcs.cursorex;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.ListIterator;
if(b.id==111)
lstr.remove();
if((b.name).equals("C"))
lstr.remove();
if(b.name.equals("CPP")){
b.name = "C++";
lstr.set(b);
}
}
package com.tcs.cursorex;
import java.util.ArrayList;
import java.util.ListIterator;
if(b.id==111)
lstr.remove();
if((b.name).equals("C"))
lstr.remove();
if(b.name.equals("CPP")){
b.name = "C++";
lstr.set(b);
}
}
books.forEach(b->System.out.println(b));
books.forEach(System.out::println);
System.out.println("OPeratiosn are completed...");
}
}
package com.tcs.cursorex;
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author +
"]";
}
}
Data Sorting
ex-1 :
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
public static <T extends Comparable<? super T>> void sort(List<T> list)
T = type of the data taken
case 2: when we perform sorting of data, if the data contains null value while
performing comparison by using compareTo() method JVM will
generate java.lang.NullPointerException.
Any object with comparision of null, you will get NullPointerException.
@FunctionalInterface
public interface Comparator<T>{
int compare(T o1,T o2)
}
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
public class SortingEx2 {
public static void main(String[] args) {
ArrayList<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(111, "ratan"));
emps.add(new Emp(444, "anu"));
emps.add(new Emp(333, "durga"));
emps.add(new Emp(222, "sravya"));
//Collections.sort(emps,(o1,o2)->o1.eid.compareTo(o2.eid));
//Collections.sort(emps,(o1,o2)->o1.ename.compareTo(o2.ename));
//emps.sort((o1,o2)->-o1.ename.compareTo(o2.ename));
emps.sort((o1,o2)->o2.ename.compareTo(o1.ename));
emps.forEach(e->System.out.println(e.eid+" "+e.ename));
}
}
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
//Collections.sort(emps,(e1,e2)->e1.eid.compareTo(e2.eid));
//Collections.sort(emps,(e1,e2)->e1.ename.compareTo(e2.ename));
emps.sort((e1,e2)->e1.ename.compareTo(e2.ename));
emps.forEach(e->System.out.println(e.eid+" "+e.ename));
}
}
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
//Collections.sort(emps,(e1,e2)->e1.eid.compareTo(e2.eid));
//Collections.sort(emps,(e1,e2)->e1.ename.compareTo(e2.ename));
emps.sort((e1,e2)->e1.ename.compareTo(e2.ename));
emps.forEach(e->System.out.println(e.eid+" "+e.ename));
}
}
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
Collections.sort(al, Comparator.comparing(Student::getName));
System.out.println("Sorting by Name");
stu.forEach(s->System.out.println(s.rollno+" "+s.name+" "+s.age));
//Sorting age
Collections.sort(al, Comparator.comparing(Student::getAge));
System.out.println("Sorting by Age");
stu.forEach(s->System.out.println(s.rollno+" "+s.name+" "+s.age));
}
}
package com.tcs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
// Collections.sort(stu,Comparator.comparing(Student::getName));
// Collections.sort(stu,Comparator.comparing(Student::getRollno));
Collections.sort(stu,Comparator.comparing(Student::getAge));
Assignmnet-1:
Book : id name author
ArrayList<Book> : insert four book objects
i. print the book object using decending order of book id.
Collections.sort(list,Comparator)
ii. print the book object using ascending order of book name.
list.sort(Comparator)
Assignmnet-2:
Product : id name cost
ArrayList : insert the product objects.
input:
pid pname pcost
1 pen 100.45
2 car 30000
4 fan 900
3 chair 400
3 laptop 40000
3 laptop 400
3 laptop 30000
2 mobile 10000
2 charger 300
ouput:
pid pname pcost
1 pen 100.45
2 car 30000
2 charger 300
2 mobile 10000
3 chair 400
3 laptop 400
3 laptop 30000
3 laptop 40000
4 fan 900
package com.tcs.list;
}
package com.tcs.list;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
Collections.sort(a1, Comparator
.comparing(Emp::getEid)
.thenComparing(Emp::getEname)
.thenComparing(Emp::getEsal));
a1.forEach(e->System.out.println(e.getEid()+" "+e.getEname()+"
"+e.getEsal()));
}
}
Iterable(i)
|
Collection(i)
|
Set(i)
HashSet(c)1.2
SortedSet(i)
|
|
LinkedHashSet(c)1.4
NavigableSet(i)
TreeSet(c) 1.2
HashSet:
1. duplicates are not allowed.
If we are trying to insert duplicates it will insert the first occurence it
will ignore next data.
2. This class permits the null element.
3. Note that this implementation is not synchronized.
4. It makes no guarantees as to the iteration order of the set.
5. underlaying data structure : HashTable
HashSet constructors:
HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial
capacity(16) and load factor(0.75).
load factor range : 0.0 to 1.0
HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial
capacity and default load factor (0.75).
ex-1 :
package com.tcs;
import java.util.HashSet;
import java.util.Iterator;
System.out.println("******");
h.forEach(System.out::println);
}
}
LinkedHashSet:
1. duplicates are not allowed.
2. null is allowed.
3. methods are non-synchronized.
4. insertion order is preserved.
5. underlaying data structure : HashTable + LinkedList
LinkedHashSet()
Constructs a new, empty linked hash set with the default initial capacity (16) and
load factor (0.75).
LinkedHashSet(int initialCapacity)
Constructs a new, empty linked hash set with the specified initial capacity and the
default load factor (0.75).
ex: LinkedHashSet
package com.tcs;
import java.util.Iterator;
import java.util.LinkedHashSet;
ex: In hashset if we are inserting duplicates first object is inserted next objects
are ignored.
package com.tcs;
import java.util.LinkedHashSet;
public class HashSetEx1 {
public static void main(String[] args) {
LinkedHashSet<String> h = new LinkedHashSet<String>();
System.out.println(h.add("ratan"));
System.out.println(h.add("ratan"));
System.out.println(h.add("ratan"));
System.out.println(h.add("ratan"));
System.out.println(h);
}
}
TreeSet:
1. The elements are ordered using their natural ordering.
2. Note that this implementation is not synchronized.
3. Duplicates are not allowed.
4. this class permits null value.
TreeSet()
Constructs a new, empty tree set, sorted according to the natural ordering of its
elements.
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering
as the specified sorted set.
package com.tcs;
import java.util.TreeSet;
public class TreeSetEx2 {
public static void main(String[] args) {
TreeSet<String> t = new TreeSet<String>((s1,s2)->-s1.compareTo(s2));
t.add("ratan");
t.add("anu");
t.add("naresh");
t.add("sravya");
System.out.println(t);
}
}
//constructor-3
TreeSet(Collection<? extends E> c)
Constructs a new tree set containing the elements in the specified collection,
sorted according to the natural ordering of its elements.
package com.tcs;
import java.util.TreeSet;
public class TreeSetEx3 {
public static void main(String[] args) {
TreeSet<String> t1 = new TreeSet<String>();
t1.add("ratan");
t1.add("anu");
//constructor-4
TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the
same ordering as the specified sorted set.
package com.tcs;
import java.util.SortedSet;
import java.util.TreeSet;
public class TreeSetcons1 {
public static void main(String[] args) {
TreeSet<Integer> t = new TreeSet<Integer>();
for(int i=1;i<=10;i++)
{ t.add(i);
}
System.out.println(t);
SortedSet<Integer> s2 = t.tailSet(4);
TreeSet<Integer> t2 = new TreeSet<Integer>(s2);
System.out.println(t2);
SortedSet<Integer> s3 = t.headSet(6);
TreeSet<Integer> t3 = new TreeSet<Integer>(s3);
System.out.println(t3);
}
}
ex:
package com.tcs.lambda;
import java.util.Arrays;
import java.util.Collections;
System.out.println("*********");
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println(Arrays.toString(numbers));
System.out.println("*********");
String[] names = new String[5];
names[0] = "ratan";
names[1] = "anu";
names[2] = "durga";
names[3] = "sravya";
names[4] = "ram";
Arrays.sort(names);
System.out.println(Arrays.toString(names));
Integer[] data = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366,
420 };
Arrays.sort(data, 2, 6);
System.out.println(Arrays.toString(data));
}
}
ex:
abc.properties
tomato = 30
grapes = 100
chiken = 100
oranges = 60
jackfruit = 700
package com.tcs.lambda;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
Map(i) 1.2
HashMap(c)1.2 SortedMap(i)1.2
| |
LinkedHashMap(c)1.4 NavigableMap(i)1.2
|
TreeMap(c)1.2
The Map is storing two objects at a time in the from of key:value pairs
HashMap<Integer, String> h = new HashMap<Integer,String>();
h.put(111, "ratan");
h.put(222, "anu");
h.put(333, "ratan");
Interface Map<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values
c. The key value pair is known as entry, the map contains group of entries.
d. In the map the keys must be unique but values we can duplicate.
3. ip no of hits
10.5.6.4 ----- 5
10.5.4.2 ----- 10
78.90.45.4 ----- 5
4. To store the form data.
text filed logical name value
username logical name ---- ratan
user pass logical name ---- ratan
HashMap 1.2:
1. HashMap is used to store two objects at a time in the form of key value pairs.
Here the key is object & value is object.
This class makes no guarantees as to the order of the map.
2. In the map the keys must be unique but values we can duplicate.
3. Hash table based implementation of the Map interface.
4. permits null values and the null key.
5. Note that this implementation is not synchronized.
Constructors:
HashMap()
Constructs an empty HashMap with the default initial capacity (16) and the
default load factor (0.75).
HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default
load factor (0.75).
HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.
package com.tcs;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
LinkedHashMap()
Constructs an empty insertion-ordered LinkedHashMap instance with the
default initial capacity (16) and load factor (0.75).
LinkedHashMap(int initialCapacity)
Constructs an empty insertion-ordered LinkedHashMap instance with the
specified initial capacity and a default load factor (0.75).
LinkedHashMap(int initialCapacity, float loadFactor)
Constructs an empty insertion-ordered LinkedHashMap instance with the
specified initial capacity and load factor.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Constructs an empty LinkedHashMap instance with the specified initial
capacity, load factor and ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m)
Constructs an insertion-ordered LinkedHashMap instance with the same
mappings as the specified map.
ex: LinkedHashMap
package com.tcs;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
Student ss = e.getValue();
System.out.println(ss.sid+" "+ss.sname);
}
package com.tcs;
import java.util.HashMap;
public class HashMapEx2{
public static void main(String[] args) {
HashMap<Integer, String> h1 = new HashMap<Integer,String>();
h1.put(111, "ratan");
h1.put(222, "anu");
System.out.println(h1);
ex : Assigment
Product : id name cost
Customer: id name number
LinkedHashMap<Product,Customer>: insert four objects
a. read the keys
b. read the values
c. read the entries : get the the using iteratror
d. Read the data using forEach() method.
HashMap : non-synchronized
Hashtable : synchronized methods.
As of the Java 2 platform v1.2, this class was retrofitted to implement the Map
interface, making it a member of the Java Collections Framework.
package com.tcs;
import java.util.Hashtable;
public class HashTableEx {
public static void main(String[] args) {
System.out.println(h);
System.out.println(h.size());
System.out.println(h.get(11));
System.out.println(h.get(111)); //[if the key is not present it
returns null]
System.out.println(h.containsKey(33));
h.remove(33);
System.out.println(h.containsKey(33));
System.out.println(h.containsValue("ratan"));
System.out.println(h.isEmpty());
h.clear();
System.out.println(h.isEmpty());
}
}
TreeMap:
1. A Red-Black tree based NavigableMap implementation.
2. The map is sorted according to the natural ordering of its keys.
3. Note that this implementation is not synchronized.
4. null is allowed for both key & value.
Constructors:
TreeMap()
Constructs a new, empty tree map, using the natural ordering of its keys.
package com.tcs;
import java.util.TreeMap;
public class TreeMapEx {
public static void main(String[] args) {
TreeMap<Integer,String> h = new TreeMap<Integer,String>();
h.put(444,"ratan");
h.put(222,"anu");
h.put(111,"aaa");
h.put(333,"ccc");
System.out.println(h);
}
}
//constructor2
TreeMap(Comparator<? super K> comparator)
Constructs a new, empty tree map, ordered according to the given comparator.
package com.tcs;
import java.util.TreeMap;
public class TreeMapEx1 {
public static void main(String[] args) {
TreeMap<Integer,String> h = new TreeMap<Integer,String>((i1,i2)->-
i1.compareTo(i2));
h.put(444,"ratan");
h.put(222,"anu");
h.put(111,"aaa");
h.put(333,"ccc");
System.out.println(h);
}
}
//constructor-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.
package com.tcs;
import java.util.TreeMap;
public class TreeMapEx3 {
public static void main(String[] args) {
TreeMap<Integer, String> t1 = new TreeMap<Integer,String>();
t1.put(10,"ratan");
t1.put(20,"anu");
TreeMap<Integer, String> t2 = new TreeMap<Integer,String>(t1);
t2.put(30,"sravya");
t2.put(40,"naresh");
System.out.println(t2);
}
}
//constructor-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.
package com.tcs;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
System.out.println("\ncomparing By Key");
map.entrySet()
.stream()
.sorted(Entry.comparingByKey())
.forEach(System.out::println);
//comparingByValue
System.out.println("\ncomparing By Value");
map.entrySet()
.stream()
.sorted(Entry.comparingByValue())
.forEach(System.out::println);
unSortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
System.out.println(sortedMap);
ex:
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
List<Integer> newvalues = new ArrayList<Integer>();
package com.tcs.list;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
ex:
package com.tcs.list;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
ex:
package com.tcs.list;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Assignment:
ArrayList<String> : {"raju","rani","anu","durga"}
Get the names are starts with r : raju rani
I need the all words number of characters : 8
System.out.println("*********");
List<Integer> values = Arrays.asList(1,2,3,4,5,6);
int res = values.stream()
.filter(i->i%2==0)
//[2,4,6]
.map(i->i+1)
//[3,5,7]
.reduce((i1,i2)->i1*i2).get();
// 105
System.out.println(res);
stream object:
stream()
filter()
map()
sorted()
collect()
forEach()
reduce()
ex-1:
package com.tcs;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.RandomAccess;
ex-2:
package com.tcs;
import java.util.ArrayList;
public class CloneingEx {
public static void main(String[] args) {
If the project is running multiple JVM instances then public modifier is not
sufficient to access the data, in this case use serialization & desrialization.
Serialization:
The process of converting java object to network supported form or file
supported form is called serialization.
The process of saving an object to a file is called serialization.
The process of writing the object to file is called serialization.
Deserialization:
The process of reading the object from file is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
Serializable is a marker interface it does not contains any methods but whenever
our class is implementing Serializable interface our class is acquiring some
capabilities to perform some operations those capabilities are provided by JVM.
//SerializeDesrializeEx.java
package com.tcs;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
transient:
preventing Serialization process by using transient modifier.
it is the modifier applicable for only variables.
if a variable declared as a transient those variables are not participated in
serialization instead of original values default values will be transfered.
//Emp.java
import java.io.*;
class Emp implements Serializable
{ transient int eid;
transient String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
Output : 0----null
ex 4: Observations
Case 1: it is not possible to serialize static data members in java.
because we are serializing the object only instance data is linked with
object.
Case 2: ****VVIP*****
class Address
{ int dno;
String street;
String state;
}
class Emp implements Serializable
{ int eid;
String ename;
Address addr;
}
It is not possible to serializale Emp class because the address class is not
serializable.
To perform the serialization of emp data the corresponding all members are must be
serializable.
To perform the Serialization of Emp data the Address class also must be
serializable.
case 3:
Rule: In case of array or collection, all the objects of array or collection must
be serializable. If any object is not serializable, serialization will be failed.
//Here the ArrayList is generic version contains only one type of object.
ArrayList<Emp> al = new ArrayList<Emp>();
To perfrom the Serialization of ArrayList the emp data must be serializable data.
//Serialization process
FileOutputStream outputStream = new FileOutputStream("abc.txt");
ObjectOutputStream objectOutputStream = new
ObjectOutputStream(outputStream);
objectOutputStream.writeObject(al);
outputStream.close();
objectOutputStream.close();
System.out.println("serialization process completed......");
//Deserialization process
FileInputStream inputStream = new FileInputStream("abc.txt");
ObjectInputStream objectInputStream = new
ObjectInputStream(inputStream);
ArrayList<Emp> arraylist =
(ArrayList<Emp>)objectInputStream.readObject();
for(Emp e:arraylist)
{ System.out.println(e.eid+"---"+e.ename);
}
outputStream.close();
objectInputStream.close();
System.out.println("Deserialization process completed......");
}
}
ex:
package com.tcs;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesEx {
public static void main(String[] args) throws IOException {
//load the properties
Properties properties = new Properties();
properties.load(new FileInputStream("abc.properties"));
import java.util.List;
import java.util.Map;
import java.util.Set;
ex:
package com.tcs.cloneserialize;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
package com.tcs.cloneserialize;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
ex-1:
package com.tcs.cursor;
import java.util.ArrayList;
import java.util.Iterator;
System.out.println("**********");
System.out.println("*******");
Iterator<String> newitr = objs.iterator();
newitr.forEachRemaining(s ->System.out.println(s));
}
}
ex-2:
package com.tcs.cursor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
System.out.println("******get() method*****");
Product product = products.get(2);
System.out.println(product.pid+" "+product.pname+" "+product.pcost);
System.out.println("*****forEach() mehthod*****");
products.forEach(p ->System.out.println(p.pid+" "+p.pname+"
"+p.pcost));
}
}
ex: Assignment:
Book : id name author
Vector<Book> : insert three Book objects
a. for-each loop read the data
b. get() method read the specefic record.
c. get the Iterator cursor apply some condition remove the data.
d. read the data using ListIterator generic version
Add one new product
apply some condition remove one object
apply some condition replace one object
e. read the data using Enumeration cursor.
f. read the data using forEach() method.
ex:
ex : Assigment
LinkedHashMap<Product:id name cost ,Customer: id name number>
insert four objects
a. read the keys
b. read the values
c. read the entries : get the the using iteratror
d. Read the data using forEach() method.