0% found this document useful (0 votes)
10 views56 pages

Collection Framework

The document provides an overview of the Java Collection Framework, highlighting the differences between arrays and collections, as well as the various classes and interfaces within the framework. It explains the characteristics of collection classes, the use of generics for type safety, and includes examples of basic operations on collections like ArrayList. Additionally, it covers the introduction of autoboxing and the evolution of collections in Java, particularly from version 1.2 onwards.

Uploaded by

kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views56 pages

Collection Framework

The document provides an overview of the Java Collection Framework, highlighting the differences between arrays and collections, as well as the various classes and interfaces within the framework. It explains the characteristics of collection classes, the use of generics for type safety, and includes examples of basic operations on collections like ArrayList. Additionally, it covers the introduction of autoboxing and the evolution of collections in Java, particularly from version 1.2 onwards.

Uploaded by

kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 56

Collection Framework

********************

1. Arrays vs. Collections:


Both Arrays and Collections are used to represent group of objects as a
single entity but the differences are as shown below.

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.

2. parts of collection framework


There are two parts
a. Collection : used to store the data in single object format [10,20,30,40]
List implementation classes : ArrayList, LinkedList , Vector,
Stack
Set implementation classes : HashSet, LinkedHashSet, TreeSet
Queue implementation classes: PriorityQueue

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

a. The root interface of the collection framework is : Collection


b. The root interface of the map is : Map

c. The collection contains parent interface :


java.lang.Iterable (java5)
d. The collection related information preseet in package : java.util

e. Collection framework introduced in : jdk


1.2 version

3. Collection vs. Collections


Collection is a root interface of collection framework.
whereas Collections is class it contains some methods to perform
operations.

4. Topics covered in Collection framework


List implementation classes : ArrayList,LinkedList, Vector , Stack
Set implementation classes : HashSet, LinkedHashSet , TreeSet
Queue implementation classes : PriorityQueue

Map implementation classes : HashMap , LinkedHashMap , TreeMap

cursors : Enumeration , Iterator ,


ListIterator
Collection sorting : Comparable , Comparator.

Cloneing & serialization : Cloneable, Serializable.


Collection stream API : filter , mapper , reduce.

Collection with generics : type safety.


Functional programming : Lambdda expression , method reference

public interface Collection<E> extends Iterable<E>


The root interface in the collection hierarchy.
A collection represents a group of objects, known as its elements.
Some collections allow duplicate elements and others do not.
Some are ordered and others unordered.

public interface List<E> extends Collection<E>


lists typically allow duplicate elements.
An ordered collection (also known as a sequence).

public interface Set<E> extends Collection<E>


A collection that contains no duplicate elements.
An un-ordered collection.

List vs. Set:


List classes allows duplicates objects. If the application requirment to
store the duplicate objects then use List implementation classes.
Set classes duplicates are not allowed. If the application reuirment is to
store the unique objects then use Set implementation classes.

List implementation classes : ArrayList,LinkedList, Vector , Stack

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

Chracterstics of collection classes:


a. Duplicate objects are allowed or not allowed.
b. An ordered collection (also known as a sequence) or unordered.
input : e1 e2 e3 output : e1 e2 e3 : ordered
input : e1 e2 e3 output : e3 e1 e2 : unordered
c. null insertion.
d. methods : synchronized or non-synchronized
java 1.0 version class methods are : synchronized
e. DS : based on DS the data will be stored internally.
List implementation classes comman behaviour:
a. All list classes duplicates are allowed.
b. An ordered collection (also known as a sequence).
c. All classes null is allowed.

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.

public class ArrayList<E> extends AbstractList<E>


implements List<E>, RandomAccess,
Cloneable, Serializable

To check the API use below link


https://docs.oracle.com/javase/8/docs/api/

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.

3. ArrayList(Collection<? extends E> c)


Constructs a list containing the elements of the specified
collection,
Adding one collection data into another collection.

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

Every collection class implemented using auto-boxing concept.


In above example we are adding primitive data but it is automatically converted to
wrapper object format is called autoboxing. Autoboxing introduced in java5 version.
primitive data : byte short int long float double char boolean
wrapper objects : Byte Short Integer Long Float Double Character Boolean

upto java 1.4 version: no auto boxing


ArrayList objs = new ArrayList();
objs.add(Double.valueOf(100.5));
objs.add(Integer.valueOf(200));

from java 1.5 version: Auto boxing


ArrayList objs = new ArrayList();
objs.add(100.5);
objs.add(200);

ex-1: Collections are not type safe


//Emp.java
package com.tcs;
public class Emp {
Integer eid;
String ename;
public Emp(int eid, String ename) {
super();
this.eid = eid;
this.ename = ename;
}
}

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

public class ArrayListEx2 {

public static void main(String[] args) {


ArrayList objs = new ArrayList();
objs.add(new Emp(111, "ratan"));
objs.add(new Student(1, "anu"));
objs.add(null);

for(Object obj : objs)


{ if(obj instanceof Emp)
{ Emp e = (Emp)obj;
System.out.println(e.eid+" "+e.ename);
}
if(obj instanceof Student)
{ Student student = (Student)obj;
System.out.println(student.sid+" "+student.sname);
}
if(obj==null)
{ System.out.println(obj);
}
}

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.

ex 2: To make the collections are type safe use generics.


package com.tcs;
import java.util.ArrayList;
public class ArrayListEx3 {
public static void main(String[] args) {
//Arrays are type safe
int[] a = {10,20,30};
for(int aa : a)
{ System.out.println(aa);
}

//Collection are not type safe


ArrayList objs = new ArrayList();
objs.add(new Emp(111, "ratan"));
objs.add(new Student(1, "anu"));
for(Object o : objs)
{ if(o instanceof Emp)
{ Emp e = (Emp)o;
System.out.println(e.eid+" "+e.ename);
}
if(o instanceof Student)
{ Student s = (Student)o;
System.out.println(s.sid+" "+s.sname);
}
}
Student ss = (Student)objs.get(1);
System.out.println(ss.sid+" "+ss.sname);

//use generics provide the type safety to collections


ArrayList<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(111, "ratan"));
emps.add(new Emp(222, "anu"));
for(Emp e : emps)
{ System.out.println(e.eid+" "+e.ename);
}
Emp e = emps.get(1);
System.out.println(e.eid+" "+e.ename);
}
}

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.

collections : java 1.2 without generics & autoboxing : no use


generics & autoboxing are introduced in java5.
java 5 version makes the collections are more powerfull.....

ex-3: Taking input from enduser adding into ArrayList object.


package com.tcs;
import java.util.ArrayList;
import java.util.Scanner;
public class Takinginput {
public static void main(String[] args) {
//Taking Different values from end user store into ArrayList.
Scanner scanner = new Scanner(System.in);

ArrayList objs = new ArrayList();


System.out.println("Enter first obj Integer");
objs.add(scanner.nextInt());
System.out.println("Enter second obj Double");
objs.add(scanner.nextDouble());
System.out.println("Enter third obj string");
objs.add(scanner.next());

//Taking 5 Integer values from end user store into ArrayList


ArrayList<Integer> intobjs = new ArrayList<Integer>();
for(int i=1;i<=5;i++)
{ System.out.println("Enter "+i+" value :");
intobjs.add(scanner.nextInt());
}
System.out.println("ArraYList Data:"+intobjs);

scanner.close();
}
}

ex-4: Basic operations on ArrayList


package com.tcs;

import java.util.ArrayList;

public class ArrayListEx4 {

public static void main(String[] args) {


ArrayList al = new ArrayList();
al.add(10);
al.add(10.5);
al.add("naresh");
al.add("ratan");
al.add(10);
al.add(null);
System.out.println(al); // 10 10.5 nearesh ratan 10 null

System.out.println(al.size()); // 6

al.add(3, "anu"); // 10 10.5 naresh anu ratan 10 null

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

add() : this method will add the data by default last


add(2,"ratan") : this method will add the data at 2nd index
size() : To find the size of the ArrayList
remove("ratan") : Used to remove the object "ratan".
remove(2) : here int value by default taking index format
set(1,"ratan") : to replace the data at 1st index.
isEmpty() : to check the ArrayList is empty or not
clear() : to remove the all elements.

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;

public class ArrayListEx4 {

public static void main(String[] args) {


ArrayList<String> objs = new ArrayList<String>(Collections.nCopies(10,
"ratan"));
objs.add("anu");
objs.add("durga");
System.out.println(objs);

ArrayList<String> a1 = new ArrayList<String>();


a1.add("ratan");
a1.add("anu");
a1.add("naresh");
a1.add("sravya");

System.out.println("Before swapping :" + a1);


Collections.swap(a1, 1, 3);
System.out.println("After swapping :" + a1);
}
}

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;

public class ArrayListEx6 {

public static void main(String[] args) {


//Constructor Approach : Adding one collection into another collection
: one to one
ArrayList<String> a1 = new ArrayList<String>();
a1.add("ratan");
a1.add("anu");
ArrayList<String> a2 = new ArrayList<String>(a1);
a2.add("rani");
a2.add("usman");
System.out.println(a2);

//addAll() Approach : Adding many Collections into another


collection : many to one
ArrayList<Integer> objs1 = new ArrayList<Integer>();
objs1.add(10);
objs1.add(20);
ArrayList<Integer> objs2 = new ArrayList<Integer>();
objs2.add(100);
objs2.add(200);

ArrayList<Integer> objs3 = new ArrayList<Integer>();


objs3.addAll(objs1);
objs3.addAll(objs2);
objs3.add(1000);
System.out.println(objs3);
}
}
add() : used to add only one object.
addAll() : used to add collection data.

ex 2: contains() vs. contiansAll()


package com.tcs;
import java.util.ArrayList;
public class ArrayListex7 {

public static void main(String[] args) {


Emp e1 = new Emp(111,"ratan");
Emp e2 = new Emp(222,"Sravya");
Emp e3 = new Emp(333,"aruna");
Emp e4 = new Emp(444,"anu");

ArrayList<Emp> a1 = new ArrayList<Emp>();


a1.add(e1);
a1.add(e2);

ArrayList<Emp> a2 = new ArrayList<Emp>();


a2.addAll(a1);
a2.add(e3);
a2.add(e4);

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

contains() : Returns true if this list contains the specified element.


containsAll() : Returns true if this collection contains all of the elements in the
specified collection.

ex 3: remove() vs. removeAll() vs. retainAll()

package com.tcs;

import java.util.ArrayList;

public class ArrayListex8 {

public static void main(String[] args) {

ArrayList<Emp> a1 = new ArrayList<Emp>();


a1.add(new Emp(111,"ratan"));
a1.add(new Emp(222,"Sravya"));
ArrayList<Emp> a2 = new ArrayList<Emp>(a1);
a2.add(new Emp(333,"aruna"));
a2.add(new Emp(444,"anu"));

a2.removeAll(a1); // here it will remove all a1 objects


a2.retainAll(a1); // here it will remove all a2 objects except
a1

for(Emp e : a2)
{ System.out.println(e.eid+" "+e.ename);
}

System.out.println("operations are completed....");


}
}

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;

public class Main {

public static void main(String[] args) {


ArrayList<Book> tech = new ArrayList<Book>();
tech.add(new Book(111, "corejava", 200.45));
tech.add(new Book(222, "advjava", 300.45));

ArrayList<Book> nontech = new ArrayList<Book>();


nontech.add(new Book(1111,"you can win", 450.45));
nontech.add(new Book(2222, "harry potter", 800.45));

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

allBooks.add(2, new Book(444,"spring", 400.54));


allBooks.remove(4);

for(Book bb : allBooks) {
System.out.println(bb.id + " " + bb.bname + " " + bb.price);
}
}
}

ex-3: Converting arrays to Collections & Collections to Arrays


1. Arrays to collection : Arrays.asList()
2. collections to arrays
a. toArray(arg) : generic version of collection to
array.
b. toArray() : normal version of collection to
array.

package com.tcs;

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListex9 {

public static void main(String[] args) {

//conversion of arrays to collections


String[] str = {"ratan","anu","sravya"};
ArrayList<String> objs = new ArrayList<String>(Arrays.asList(str));
objs.add("aaa");
objs.add("bbb");
System.out.println(objs);
System.out.println("***********");

//generic version Collections to Arrays


ArrayList<String> a1 = new ArrayList<String>();
a1.add("ratan");
a1.add("anu");
a1.add("sravya");

String[] s = new String[a1.size()];


a1.toArray(s);
for(String ss : s)
{ System.out.println(ss);
}
System.out.println("***********");

//normal version collection to Array


ArrayList data = new ArrayList();
data.add(10);
data.add("ratan");
data.add(10.5);
Object[] o = data.toArray();
for(Object oo : o)
{ System.out.println(oo);
}
System.out.println("***********");
}
}

import java.util.*;
class Test
{ public static void main(String[] args)
{ List<String> data = List.of("ratan","anu","sravya");
System.out.println(data);

Student s1 = new Student(111,"ratan",98);


Student s2 = new Student(222,"anu",68);
Student s3 = new Student(333,"sravya",88);

List<Student> studentdata = List.of(s1,s2,s3);


for(Student s : studentdata)
{ System.out.println(s.sid+" "+s.sname+" "+s.marks);
}
}
}

ArrayList vs. Vector(java1.0):


ArrayList & Vector both are same.
ArrayList : methods are non-synchronized : more than one thread can
access : not thread safe
Vector : methods are synchronized : only one thread can
access : thread safe.

If the Thread-safe implementation is needed then use : Vector


If the Thread-safe implementation is not needed then use : ArrayList

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.

Vector(int initialCapacity, int capacityIncrement)


Constructs an empty vector with the specified initial capacity and capacity
increment.

Vector(Collection<? extends E> c)


Constructs a vector containing the elements of the specified collection,
Adding one collection data into another collection.

ex: All Vector class constructors.


package com.tcs;

import java.util.ArrayList;
import java.util.Vector;

public class VectorEx1 {

public static void main(String[] args) {


Vector<String> objects = new Vector<String>();
objects.add("ratan");
objects.add("anu");
objects.add("naresh");
System.out.println(objects.capacity());

System.out.println("********");

Vector<String> objs = new Vector<String>(3);


System.out.println(objs.capacity());
objs.add("ratan");
objs.add("anu");
objs.add("sravya");
objs.add("naresh");
System.out.println(objs.capacity());

System.out.println("********");

Vector<String> data = new Vector<String>(2,6);


System.out.println(data.capacity());
data.add("ratan");
data.add("anu");
data.add("sravya");
System.out.println(data.capacity());

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

Vector v = new Vector(); //10

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.

ex-1: operataions on LinkedList


import java.util.*;
class Test
{ public static void main(String[] args)
{ LinkedList<String> l = new LinkedList<String>();
l.add("B");
l.add("C");
l.add("D");
l.add("E");
l.addLast("Z");
l.addFirst("A");
l.add(1,"A1");
System.out.println("original content:-"+l);

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

ex 2: we can add any collection data into any collection.


Here we are adding ArrayList data into LinkedList

import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("ram");

LinkedList<String> linked = new LinkedList<String>(al);


linked.add("anu");
System.out.println(linked);
}
}
ArrayList vs. LinkedList:
1. ArrayList internally uses resizable array Data structure to store the
elements.
So the data stored in array format.
LinkedList internally uses double linkedlist implementation to store the
elements.
So the data stored in double linked list format.

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.

3. search operartions ArrayList is good it is index based.


Element retrieval in ArrayList is much faster then LinkedList, ArrayList take
O(1) of time to retrieve any location where LinkedList take O(n) time to retrieve
the element.

However, unlike arrays which allow random access to the elements contained
within them, a link list only allows sequential access to its elements.

4. with respect to memory ArrayList is Good . it stores only data.


LinkedList stores the data & next link address.
Linked lists also use more storage space in a computer memory as each node in
the list contains both a data item and a reference to the next node.

5. ArrayList is implements RandomAccess marker interface hence the data Access


fast.
But LinkedList not implementing RandomAccess interface hence the data Access
slow.

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

List al = new ArrayList(); // valid & 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);
}
}

public static void m2(List<String> objs)


{ for (String str : objs)
{ System.out.println(str);
}
}

public static void main(String[] args)


{
ArrayList<String> data = new ArrayList<String>();
data.add("ratan");
data.add("anu");
data.add("sravya");

LinkedList<String> l = new LinkedList<String>();


l.add("aaa");
l.add("bbb");

Test.m1(data); // this code will work because we are passing


ArrayList

/* Test.m1(l); // this code will not work beacuse we are


passing LinkedList Data
incompatible types: LinkedList<String> cannot be converted to
ArrayList<String>
*/

System.out.println("*********");

Test.m2(data); // this code will work because we are passing ArrayList

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

//This code will work if the getObjects() returns only ArrayList


//getObjects() return type changed to ArrayList to LinkedList then
below code will not work
ArrayList<String> objs = Ramya.getObjects();
System.out.println(objs);

//This code will work if the getObjects() returns ArrayList()


LinkedList() Vector() Stack()
List<String> newobjs = Ramya.getObjects();
System.out.println(newobjs);
}
}

package com.tcs.listexamples;

import java.util.ArrayList;
import java.util.List;

public class TestEx2 {

public static ArrayList<String> m1()


{ ArrayList<String> objs = new ArrayList<String>();
objs.add("ratan");
objs.add("anu");
objs.add("sravya");
return objs;
}

public static List<String> m2()


{ ArrayList<String> objs = new ArrayList<String>();
objs.add("ratan");
objs.add("anu");
objs.add("sravya");
return objs;
}

public static void main(String[] args) {

}
}

we can read the data from collection classes in four ways


1. using for-each loop.
2. using get method.
3. using cursors
a. Enumeration
b. Iterator
c. ListIterator
4. forEach() method.

a. Enumeration(i): java 1.0


Using this we can read the data from only legacy classes(java 1.0).So it is
not a universal cursor.
ex: Vector,Stack

We will get Enumeration object using elements() method.


Enumeration e = v.elements();

To check the methods use javap command


E:\>javap java.util.Enumeration
public interface java.util.Enumeration<E> {
public abstract boolean hasMoreElements(); : To check the
data is available or not.
public abstract E nextElement(); : To read
the data
}

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.

Using this cursor we can do only read operations.


Using this cursor we can read the data only forward direction.

b. Iterator(i) : java 1.2 version


Using this cursor we can read the data from all collection classes, so it is
universal.

We will get this object using iterator() method.


Iterator itr = arraylist.iterator();

To check the methods use javap command


E:\>javap java.util.Iterator
public interface java.util.Iterator<E> {
public abstract boolean hasNext(); : To check the data is
available or not.
public abstract E next(); : To read the data
public void remove(); : To remove the data
public void forEachRemaining(java.util.function.Consumer); : To read
the data using lambda
}

Using this cursor we can do read & remove operations.


Using this cursor we can read the data only forward direction.

c. ListIterator(i) : java 1.2 version


Using this cursor we can read the data from only List implmentation
classes,so it is not a universal

We will get this object using listIterator() method.


ListIterator itr = arraylist.listIterator();

To check the methods use javap command


E:\>javap java.util.ListIterator
public interface java.util.ListIterator<E> extends
java.util.Iterator<E> {
public abstract boolean hasNext();
public abstract E next();

public abstract boolean hasPrevious();


public abstract E previous();

public abstract int nextIndex();


public abstract int previousIndex();

public abstract void remove();


public abstract void set(E);
public abstract void add(E);
}

Using this cursor we can do read,remove,update,add operations.


Using this cursor we can read the data forward & backword direction.

ArrayList(1.2) : Iterator , ListIterator


Vector(1.0) : Enumeration, Iterator, ListIterator
HashSet(1.2) : Iterator

ex-1:
package com.tcs.cursors;

import java.util.ArrayList;
import java.util.Iterator;

public class Test1 {

public static void main(String[] args) {


ArrayList<String> objs = new ArrayList<String>();
objs.add("ratan");
objs.add("anu");
objs.add("naresh");
objs.add("sravya");
System.out.println("****for-each loop***");
for(String s : objs)
{ System.out.println(s);
}

System.out.println("***Get() method****");
String name = objs.get(2);
System.out.println(name);

System.out.println("****Iterator normal version***");


Iterator itr = objs.iterator();
while(itr.hasNext())
{ String s = (String)itr.next();
System.out.println(s);
}

System.out.println("****Iterator generic version***");


Iterator<String> gitr = objs.iterator();
while(gitr.hasNext())
{ String s = gitr.next();
System.out.println(s);
}

System.out.println("****Iterator lambda version***");


Iterator<String> itr1 = objs.iterator();
itr1.forEachRemaining(s->System.out.println(s));

System.out.println("****Iterator method-reference version***");


Iterator<String> itr2 = objs.iterator();
itr2.forEachRemaining(System.out::println);

System.out.println("******forEach() using lambda*******");


objs.forEach(s->System.out.println(s));

System.out.println("******forEach() using method-reference*******");


objs.forEach(System.out::println);
}
}

default void forEach(Consumer<? super T> action)


default void forEachRemaining(Consumer<? super E> action)

@FunctionalInterface
public interface Consumer<T>{
void accept(T t)
}

Consumer is a Functional interface present in package java.util.function


Consumer is a functional interface contains only one abstract method is
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;

public class CursorEx2 {

public static void main(String[] args) {


ArrayList<String> objects = new ArrayList<String>();
objects.add("ratan");
objects.add("anu");
objects.add("naresh");

Iterator<String> itr = objects.iterator();


while(itr.hasNext())
{ String s = itr.next();
if(s.equals("naresh"))
itr.remove();
}
System.out.println(objects);
}
}

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

ListIterator<String> glistitr = objs.listIterator();


glistitr.add("lipika");

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

ex-4: Reading the data forward & backward direction.


package com.tcs;
import java.util.ArrayList;
import java.util.ListIterator;

public class CursorEx4 {

public static void main(String[] args) {


ArrayList<String> objects = new ArrayList<String>();
objects.add("ratan");
objects.add("anu");
objects.add("naresh");

ListIterator<String> lstr = objects.listIterator();


while(lstr.hasNext())
{ String s = lstr.next();
System.out.println(s);
}

System.out.println("*******");

while(lstr.hasPrevious())
{ String str = lstr.previous();
System.out.println(str);
}
}
}

ex-5: Reading the data from specific index.


import java.util.*;
class Test
{ public static void main(String[] args)
{
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("ratan");
arrlist.add("anu");
arrlist.add("sravya");
arrlist.add("durga");

ListIterator<String> iterator = arrlist.listIterator(2);


while (iterator.hasNext())
{ String s = iterator.next();
System.out.println(s);
}
}
}

ex:
package com.tcs.cursorex;

import java.util.ArrayList;
import java.util.ListIterator;

public class CursorEx2 {

public static void main(String[] args) {


ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("ratan");
arrlist.add("anu");
arrlist.add("sravya");
arrlist.add("durga");

ListIterator<String> iterator = arrlist.listIterator(arrlist.size());


while (iterator.hasPrevious())
{ String s = iterator.previous();
System.out.println(s);
}
}
}

ex-6: Using cursor working with object data.


package com.tcs.cursorex;

import java.util.ArrayList;
import java.util.ListIterator;

public class CursorEx3 {

public static void main(String[] args) {


ArrayList<Book> books = new ArrayList<Book>();
books.add(new Book(111, "java", "ratan"));
books.add(new Book(222, "C", "anu"));
books.add(new Book(333, "CPP", "durga"));

ListIterator<Book> lstr = books.listIterator();


lstr.add(new Book(444, "Spring", "ratan"));
while(lstr.hasNext())
{ Book b = lstr.next();

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.id+" "+b.name+" "+b.author));


System.out.println("OPeratiosn are completed...");
}
}

package com.tcs.cursorex;

import java.util.ArrayList;
import java.util.ListIterator;

public class CursorEx3 {

public static void main(String[] args) {


ArrayList<Book> books = new ArrayList<Book>();
books.add(new Book(111, "java", "ratan"));
books.add(new Book(222, "C", "anu"));
books.add(new Book(333, "CPP", "durga"));

ListIterator<Book> lstr = books.listIterator();


lstr.add(new Book(444, "Spring", "ratan"));
while(lstr.hasNext())
{ Book b = lstr.next();

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.id+" "+b.name+" "+b.author));

books.forEach(b->System.out.println(b));

books.forEach(System.out::println);
System.out.println("OPeratiosn are completed...");
}
}

package com.tcs.cursorex;

public class Book {


int id;
String name;
String author;

public Book(int id, String name, String author) {


super();
this.id = id;
this.name = name;
this.author = author;
}

@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author +
"]";
}
}

Data Sorting

if we want to perform sorting data it must satisfies the below conditions,


a. The data must be homogenous.
b. Must implements Comparable interface.

Note : In java String,all wrapper classes are implementing comparable interface by


default.

ex-1 :
package com.tcs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;

public class SortingEx {


public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
al.add("naresh");
System.out.println("ArrayList data before sorting="+al);
Collections.sort(al);
System.out.println("ArrayList data after sorting="+al);

LinkedList<Integer> l = new LinkedList<Integer>();


l.add(10);
l.add(3);
l.add(20);
l.add(5);
System.out.println("Before sorting: "+l);
Collections.sort(l);
System.out.println("After sorting: "+l);
}
}

public static <T extends Comparable<? super T>> void sort(List<T> list)
T = type of the data taken

Note : To perform sorting internally JVM uses compareTo() method.


ratan ratan = 0 no change
anu ratan = -ve no change
ratan anu = +ve change

case 1: if we are trying to perform sorting of heterogeneous data ,while performing


comparison by using comapreTo() method JVM will generate
java.lang.ClassCastException.
Using compareTo() not possible to compare two different objects.
ArrayList al = new ArrayList();
al.add("ratan");
al.add(10);
Collections.sort(al);

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.

ArrayList al = new ArrayList();


al.add("ratan");
al.add(null);
Collections.sort(al);

Comparable(java.lang) : we can do default sorting(String,all wrapper).


Comparator(java.util) : This is only for custamized sorting(Emp)
predefined classes are not implementing
Comparator.
ex: we can do the sorting in two ways
a. Collections.sort() : this is for all classes.

sort() method is overloded method.


1. sort(1-arg) : this is for only comparable data sorting
public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural
ordering of its elements. All elements in the list must implement the Comparable
interface.
Here it uses e1.compareTo(e2) to perform the sorting.
This method will work only for String,All wrapper classes.

2. sort(1-arg,2-arg) : this is custamized data sorting


public static <T> void sort(List<T> list,Comparator<? super>)
Sorts the specified list according to the order induced by the
specified comparator.

@FunctionalInterface
public interface Comparator<T>{
int compare(T o1,T o2)
}

b. list.sort() : this is only for list classes.


default void sort(Comparator<? super E> c)
Sorts this list according to the order given by the specified
Comparator.

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;

public class SortEx1 {

public static void main(String[] args) {


ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
al.add("naresh");
Collections.sort(al);
System.out.println("ArrayList data sorting="+al);

LinkedList<Integer> l = new LinkedList<Integer>();


l.add(10);
l.add(3);
l.add(20);
l.add(5);
Collections.sort(l);
System.out.println("LinkedList Data sorting: "+l);

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

public class SortEx1 {

public static void main(String[] args) {

ArrayList<String> al = new ArrayList<String>();


al.add("ratan");
al.add("anu");
al.add("sravya");
al.add("naresh");
Collections.sort(al);
System.out.println("ArrayList data sorting="+al);

LinkedList<Integer> l = new LinkedList<Integer>();


l.add(10);
l.add(3);
l.add(20);
l.add(5);
Collections.sort(l);
System.out.println("LinkedList Data sorting: "+l);
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,(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));
}
}

ex: Data sorting with method reference


package com.tcs;
public class Student {
int rollno;
String name;
int age;
public Student(int rollno, String name, int age) {
super();
this.rollno = rollno;
this.name = name;
this.age = age;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

package com.tcs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListSorting {

public static void main(String[] args) {


ArrayList<Student> stu = new ArrayList<Student>();
stu.add(new Student(101, "ratan", 25));
stu.add(new Student(106, "anu", 27));
stu.add(new Student(105, "sravya", 21));

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;

public class SortEx2 {

public static void main(String[] args) {


ArrayList<Student> stu = new ArrayList<Student>();
stu.add(new Student(101, "ratan", 25));
stu.add(new Student(106, "anu", 27));
stu.add(new Student(105, "sravya", 21));

// Collections.sort(stu,Comparator.comparing(Student::getName));

// Collections.sort(stu,Comparator.comparing(Student::getRollno));

Collections.sort(stu,Comparator.comparing(Student::getAge));

stu.forEach(s->System.out.println(s.rollno+" "+s.name+" "+s.age));


}
}

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

Sort the data based on product id.


If the ID is same sort the data based on product name.
If the name is same then sort the data according to cost.

package com.tcs.list;

public class Emp {


int eid;
String ename;
double esal;
public Emp(int eid, String ename, double esal) {
super();
this.eid = eid;
this.ename = ename;
this.esal = esal;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getEsal() {
return esal;
}
public void setEsal(double esal) {
this.esal = esal;
}

}
package com.tcs.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListBasicEx4 {


public static void main(String[] args) {

ArrayList<Emp> a1 = new ArrayList<Emp>();


a1.add(new Emp(111, "ratan", 1000.45));
a1.add(new Emp(111, "anu", 3000.45));
a1.add(new Emp(111, "durga", 5000.45));
a1.add(new Emp(222, "raju", 4000.45));
a1.add(new Emp(222, "raju", 10000.45));
a1.add(new Emp(222, "raju", 2000.45));
a1.add(new Emp(1, "rani", 1000.45));

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

List vs. Set :


List duplicates are allowed.
Set duplicates are not allowed.

Iterable(i)
|
Collection(i)
|
Set(i)

HashSet(c)1.2
SortedSet(i)
|
|
LinkedHashSet(c)1.4
NavigableSet(i)

TreeSet(c) 1.2

Set implementation classes : HashSet , LinkedHashSet , TreeSet

HashSet vs. LinkedHashSet :


HashSet insertion order not preserved.
LinkedHashSet insertion order is preserved.

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

HashSet(int initialCapacity, float loadFactor)


Constructs a new, empty set; the backing HashMap instance has the specified initial
capacity and the specified load factor.

HashSet(Collection<? extends E> c)


Constructs a new set containing the elements in the specified collection.

ex-1 :
package com.tcs;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetEx1 {

public static void main(String[] args) {


HashSet<String> h = new HashSet<String>();
h.add("ratan");
h.add("anu");
h.add("durga");
h.add("ratan");

Iterator<String> itr = h.iterator();


while (itr.hasNext())
{ String str = itr.next();
System.out.println(str);
}
System.out.println("******");

h.forEach(s -> System.out.println(s));

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

LinkedHashSet(int initialCapacity, float loadFactor)


Constructs a new, empty linked hash set with the specified initial capacity and
load factor.

LinkedHashSet(Collection<? extends E> c)


Constructs a new linked hash set with the same elements as the specified
collection.

ex: LinkedHashSet
package com.tcs;

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetEx {


public static void main(String[] args) {
LinkedHashSet<String> h = new LinkedHashSet<String>();
h.add("ratan");
h.add("anu");
h.add("durga");
h.add("ratan");

Iterator<String> itr = h.iterator();


while (itr.hasNext())
{ String str = itr.next();
System.out.println(str);
}
}
}

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

TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering
as the specified sorted set.

ex: TreeSet : the data stored in sorting order.


//constructor-1
TreeSet(): Constructs a new, empty tree set, sorted according to the natural
ordering of its elements.
package com.tcs;
import java.util.TreeSet;
public class TreeSetcons1 {
public static void main(String[] args) {
TreeSet<String> t = new TreeSet<String>();
t.add("ratan");
t.add("anu");
t.add("naresh");
t.add("sravya");
System.out.println(t);

TreeSet<Integer> t1 = new TreeSet<Integer>();


t1.add(10);
t1.add(2);
t1.add(3);
t1.add(4);
System.out.println(t1);
}
}

//constructor-2 : taking separate class passing that object.


TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.

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

TreeSet<String> t2 = new TreeSet<String>(t1);


t2.add("aaa");
t2.add("bbb");
System.out.println(t2);
}
}

//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> s1 = t.subSet(3, 7);


TreeSet<Integer> t1 = new TreeSet<Integer>(s1);
System.out.println(t1);

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

public class Arrays extends Object


This class contains various methods for manipulating arrays (such as sorting
and searching).
The methods in this class all throw a NullPointerException, if the specified
array reference is null,

ex:
package com.tcs.lambda;

import java.util.Arrays;
import java.util.Collections;

public class ArraysEx {


public static void main(String[] args) {

Integer[] numbers = new Integer[] { 4,90,6,89,45,33,12,97};


Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));

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;

public class PropertiesEx {

public static void main(String[] args) throws FileNotFoundException,


IOException {

//load the properties file


Properties properties = new Properties();
properties.load(new FileReader("abc.properties"));

//read the data from properties file


System.out.println(properties.get("tomato"));
System.out.println(properties.get("jackfruit"));
System.out.println(properties.get("grapes"));
System.out.println(properties.get("oranges"));
System.out.println(properties.get("chiken"));
}
}

Map(i) 1.2

HashMap(c)1.2 SortedMap(i)1.2
| |
LinkedHashMap(c)1.4 NavigableMap(i)1.2
|

TreeMap(c)1.2

Collections vs. Map :


The collections are storing the data in single object format.
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);

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

a. An object that maps keys to values.


A map cannot contain duplicate keys; each key can map to at most one value.
b. Map is used to store two objects at a time in the form of key value pairs.
Here the key is object & value is object.

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.

1. To store the group of objects.


keys values
references objects
str1 ----- ratan
str2 ----- anu
str3 ----- ratan

2. To count the word occurence.


ratan ---- 5
anu ------ 2
is ----- 5

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 vs. LinkedHashMap :


HashMap insertion order is not preserved.
LinkedHashMap insertion order is preserved.

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.

To get all the keys use : keySet()


To get all the values : values()
To get the key,values : entrySet()

package com.tcs;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapEx {

public static void main(String[] args) {


HashMap<Integer, String> h = new HashMap<Integer,String>();
h.put(111, "ratan");
h.put(22, "anu");
h.put(333, "naresh");
h.put(44, "sravya");
System.out.println(h);

//reading the only keys using : keySet()


Set<Integer> s = h.keySet();
System.out.println(s);

//reading the values using : values()


Collection<String> v = h.values();
System.out.println(v);

//Reading the both key,value using : entrySet()


Set<Entry<Integer,String>> ss = h.entrySet();
Iterator<Entry<Integer,String>> itr = ss.iterator();
while(itr.hasNext())
{ Entry<Integer,String> e = itr.next();
Integer key = e.getKey();
System.out.println(key);

String value = e.getValue();


System.out.println(value);
}

//Reading the data using forEach(BiConsumer bi)


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

LinkedHashMap java 1.4:


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 with predictable iteration order.
2. In the map the keys must be unique but values we can duplicate.
3. Hash table and linked list implementation of the Map interface.
4. permits null values and the null key.
5. Note that this implementation is not synchronized.

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;

public class LinkedHashMapEx {

public static void main(String[] args) {


LinkedHashMap<Emp, Student> h = new LinkedHashMap<Emp,Student>();
h.put(new Emp(111, "ratan"),new Student(1, "aaa"));
h.put(new Emp(222, "anu"),new Student(2, "bbb"));
h.put(new Emp(333, "naresh"),new Student(3, "ccc"));
Set<Entry<Emp, Student>> s = h.entrySet();
Iterator<Entry<Emp, Student>> itr = s.iterator();
while(itr.hasNext())
{
Entry<Emp, Student> e = itr.next();
Emp ee = e.getKey();
System.out.println(ee.eid+" "+ee.ename);

Student ss = e.getValue();
System.out.println(ss.sid+" "+ss.sname);
}

//forEach() method to read the data


h.forEach((k,v)->System.out.println(k.eid+" "+k.ename+" \n "+v.sid+"
"+v.sname))
}
}

ex-3: Addiging one map data into another map.


There are two ways to add the one map data into another map,
a. using constructor
b. using putAll() method

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

HashMap<Integer, String> h2 = new HashMap<Integer,String>(h1);


h2.put(333, "ratan");
h2.put(444, "ratan");
System.out.println(h2);

//by using putAll() to add the data : many to one.


LinkedHashMap<Integer,String> h11 = new
LinkedHashMap<Integer,String>();
h11.put(111,"ratan");
h11.put(222,"anu");
LinkedHashMap<Integer,String> h22 = new
LinkedHashMap<Integer,String>();
h22.put(222,"aaa");
h22.put(333,"bbb");
LinkedHashMap<Integer,String> h33 = new
LinkedHashMap<Integer,String>();
h33.putAll(h11);
h33.putAll(h22);
h33.put(333,"sravya");
System.out.println(h33);
}
}

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.

ex: Hashtable vs. HashMap


Hashtable()
Constructs a new, empty hashtable with a default initial capacity (11) and
load factor (0.75).
Hashtable(int initialCapacity)
Constructs a new, empty hashtable with the specified initial capacity and
default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor)
Constructs a new, empty hashtable with the specified initial capacity and the
specified load factor.
Hashtable(Map<? extends K,? extends V> t)
Constructs a new hashtable with the same mappings as the given Map.

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

Hashtable<Integer,String> h = new Hashtable<Integer,String>();


h.put(11,"ratan");
h.put(22,"anu");
h.put(33,"sravya");

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.

TreeMap(Comparator<? super K> comparator)


Constructs a new, empty tree map, ordered according to the given comparator.

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.

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.

ex: TreeMap : the data is stored in sorting in sorting order.


//constructor-1
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;

public class TreeMapEx4 {


public static void main(String[] args) {
TreeMap<Integer, String> t = new TreeMap<Integer,String>();
t.put(10,"ratan");
t.put(20,"anu");
t.put(5,"durga");
t.put(6,"sravya");
t.put(1,"aaa");

SortedMap<Integer, String> sm = t.subMap(5, 20);


TreeMap<Integer, String> tt = new TreeMap<Integer,String>(sm);
System.out.println(tt);

SortedMap<Integer, String> sm1 = t.tailMap(10);


TreeMap<Integer, String> t1 = new TreeMap<Integer,String>(sm1);
System.out.println(t1);

SortedMap<Integer, String> sm2 = t.headMap(10);


TreeMap<Integer, String> t2 = new TreeMap<Integer,String>(sm2);
System.out.println(t2);
}
}

ex: Sorting the HashMap Data.


package com.tcs;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapEx3 {

public static void main(String[] args) {


Map<Integer, String> map = new HashMap<Integer, String>();
map.put(101, "anu");
map.put(1, "sravya");
map.put(55, "durga");
map.put(3, "ram");
map.put(77, "ratan");

System.out.println("\ncomparing By Key");
map.entrySet()
.stream()
.sorted(Entry.comparingByKey())
.forEach(System.out::println);

System.out.println("\ncomparingByKey() in descending order");


map.entrySet()
.stream()
.sorted(Entry.comparingByKey(Comparator.reverseOrder()))
.forEach(System.out::println);

//comparingByValue
System.out.println("\ncomparing By Value");
map.entrySet()
.stream()
.sorted(Entry.comparingByValue())
.forEach(System.out::println);

//comparingByValue() in descending order


System.out.println("\ncomparing By Value() in descending order");
map.entrySet()
.stream()
.sorted(Entry.comparingByValue(Comparator.reverseOrder()))
.forEach(System.out::println);
}
}

//LinkedHashMap preserve the ordering of elements in which they are inserted


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

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;

public class ArrayListBasicEx5 {

public static void main(String[] args) {


List<Integer> values = Arrays.asList(1,2,2,3,4,8,8,5,6,6);
values.stream()
.filter(x->x%2==0)
.forEach(System.out::println);

List<Integer> evenList = values.stream()


.filter(x->x%2==0)
.collect(Collectors.toLi
st());
System.out.println(evenList);

Set<Integer> evenSet = values.stream()


.filter(x->x%2==0)
.collect(Collectors.toSe
t());
System.out.println(evenSet);
}
}

ex:
package com.tcs.list;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ArrayListBasicEx6 {

public static void main(String[] args) {


List<Integer> marks = Arrays.asList(88,77,45,45,34,12,12,2);
marks.stream()
.map(x->x+2)
.forEach(System.out::println);

List<Integer> newListMarks = marks.stream()


.map(x->x+2)
.collect(Collector
s.toList());
System.out.println(newListMarks);

Set<Integer> newSetMarks = marks.stream()


.map(x->x+2)
.collect(Collectors.toSe
t());
System.out.println(newSetMarks);
}
}

ex:
package com.tcs.list;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayListBasicEx7 {

public static void main(String[] args) {


List<Integer> values = Arrays.asList(1,2,9,11,77,3,4,5);

List<Integer> evenValues = values.stream()


.filter(x->x%2==0)
.collect(Collectors.to
List());
System.out.println(evenValues);

List<Integer> maperValues = evenValues.stream()


.map(x-
>x+10)
.collect(Col
lectors.toList());
System.out.println(maperValues);

int res = maperValues.stream()


.reduce((o1,o2)->o1+o2)
.get();
System.out.println(res);
}
}

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

Cloning Process vs. Serializaion


Every collection class implements Cloneable,Serializable interfaces to support
cloneing process & serialization process.

Cloneable : it will give cloneing Capabilities


Serializable : it will serialization Capabilities

public class ArrayList<E> extends AbstractList<E>


implements List<E>,RandomAccess,Cloneable,
Serializable

public class LinkedList<E> extends AbstractSequentialList<E>


implements List<E>, Deque<E>, Cloneable,
Serializable

public class HashSet<E> extends AbstractSet<E>


implements Set<E>, Cloneable, Serializable

public class HashMap<K,V> extends AbstractMap<K,V>


implements Map<K,V>, Cloneable, Serializable

public interface Cloneable


A class implements the Cloneable interface to indicate to the Object.clone()
method that it is legal for that method to make a field-for-field copy of instances
of that class.
If the class does not implement the Cloneable interface results in the
exception CloneNotSupportedException being thrown.

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;

public class TypeCheckEx {

public static void main(String[] args) {


ArrayList<String> al = new ArrayList<String>();
System.out.println(al instanceof Iterable);
System.out.println(al instanceof Collection);
System.out.println(al instanceof List);

System.out.println(al instanceof Cloneable);


System.out.println(al instanceof Serializable);
System.out.println(al instanceof RandomAccess);
}
}

ex-2:
package com.tcs;
import java.util.ArrayList;
public class CloneingEx {
public static void main(String[] args) {

ArrayList<String> objs = new ArrayList<String>();


objs.add("anu");
objs.add("ratan");
objs.add("sravya");
System.out.println(objs);

ArrayList<String> copydata = (ArrayList<String>) objs.clone();


copydata.add("aaa");
System.out.println(copydata);
}
}

//Serialization vs. Deserialization:


with in the JVM instance just public modifier is sufficient to get the permission.
JVM1
m1 m2

If the project is running multiple JVM instances then public modifier is not
sufficient to access the data, in this case use serialization & desrialization.

JVM-1 n/w JVM-2


m1 file m2

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.

To do the serialization we required fallowing classes


1. FileOutputStream
2. ObjectOutputStream

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

The perform serialization our class must implements Serializable interfaces.

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.

Serializability of a class is enabled by the class implementing the


java.io.Serializable interface. Classes that do not implement this interface will
not have any of their state serialized or deserialized.

ex-1 : Here we are doing Serialization & deserialization of Emp data.


//Emp.java
import java.io.Serializable;
class Emp implements Serializable
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid = eid;
this.ename = ename;
}
}

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

public class SerializeDesrializeEx {

public static void main(String[] args) throws IOException,


ClassNotFoundException {
Emp emp = new Emp(111,"ratan");

// serializing the emp object : writing the object to file


FileOutputStream outputStream = new FileOutputStream("abc.txt");
ObjectOutputStream objectOutputStream = new
ObjectOutputStream(outputStream);
objectOutputStream.writeObject(emp);
objectOutputStream.close();
System.out.println("Serialization process completed.....");

//deserialization of emp object : reading the object from file


FileInputStream inputStream = new FileInputStream("abc.txt");
ObjectInputStream objectInputStream = new
ObjectInputStream(inputStream);
Emp e = (Emp)objectInputStream.readObject();
System.out.println(e.eid+" "+e.ename);
objectInputStream.close();
System.out.println("Deserialization process completed.....");
}
}

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-2: It is possible to serialize & Deserialize mutliple objects.


class Dog implements Serializable
{ }
class Cat implements Serializable
{ }
class Test
{ void serialization() throws Exception
{ Emp e = new Emp(111,"ratan");
Dog d = new Dog();
Cat c = new Cat();
//serialization [write the object to file]
FileOutputStream fos = new FileOutputStream("xxx.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.writeObject(d);
oos.writeObject(c);
System.out.println("serialization of multiple objetcs completed");
}

void deserialization() throws Exception


{ //deserialization [read object form text file]
FileInputStream fis = new FileInputStream("xxxx.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Emp e = (Emp)ois.readObject();//returns Object
Dog d = (Dog)ois.readObject();
Cat c = (Cat)ois.readObject();
System.out.println(e.eid+"----"+e.ename);
System.out.println(d);
System.out.println(c);
System.out.println("deserialization completed");
}
public static void main(String[] args) throws Exception
{ Test t = new Test();
t.serialization();
t.deserialization();
}
}
Note : It is possible to serialize the multiple objects but in which order we
serialize same order we have to desrialize otherwise JVM will generate
ClassCastException.

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.

class Data implements Serializable


{ static int eid=111;
}

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.

//Here the ArrayList is normal version contains differnet types of objects.


ArrayList al = new ArrayList();
al.add(new Emp());
al.add(new Student());
al.add(new Customer());
To perfrom the Serialization of ArrayList the Emp,Student,Customer data must be
serializable data.

ex-3 : Serialization process : To perform serialization the class must


implements Serializable interface.
package com.dss;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
ArrayList<Emp> al = new ArrayList<Emp>();
al.add(new Emp(111, "ratan"));
al.add(new Emp(222, "anu"));

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

Conversion of non-synchronized version to synchronized version:


List list = Collections.synchronizedList(new ArrayList(...));
List list = Collections.synchronizedList(new LinkedList(...));

Set s = Collections.synchronizedSet(new HashSet(...));


Set s = Collections.synchronizedSet(new LinkedHashSet(...));
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

Map m = Collections.synchronizedMap(new HashMap(...));


Map m = Collections.synchronizedMap(new LinkedHashMap(...));
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

ex: properties file


To get the flexbility of modifications we have two ways
a. using properties
b. using xml file

Properties file is normal text file with extension .properties.


The properties file contains the data in key=value pair format.
here both key,value are by default string format.
properties file keys must be unique but values can be duplicated.
While reading the properties file data if we taken key is wrong we will get null
value.

Create the properties file under the project folder.


//abc.properties : create the file in project folder.
ip = 10.40.50.60
username = ratan
password = ratan
port = 8888

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

//read the data from the properties file


System.out.println(properties.getProperty("ip"));
System.out.println(properties.getProperty("username"));
System.out.println(properties.getProperty("password"));
System.out.println(properties.getProperty("port"));
}
}

ex: Including all Collections data


package com.tcs.cloneserialize;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Services {


public List<String> names;
public Set<Integer> pincodes;
public Map<String,Integer> wordCount;

public List<String> getNames() {


return names;
}
public void setNames(List<String> names) {
this.names = names;
}

public Set<Integer> getPincodes() {


return pincodes;
}
public void setPincodes(Set<Integer> pincodes) {
this.pincodes = pincodes;
}

public Map<String, Integer> getWordCount() {


return wordCount;
}
public void setWordCount(Map<String, Integer> wordCount) {
this.wordCount = wordCount;
}
}

ex:
package com.tcs.cloneserialize;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

public class TestClient {

public static void main(String[] args) {

ArrayList<String> names = new ArrayList<String>();


names.add("ratan");
names.add("anu");
names.add("sravya");

HashSet<Integer> pincodes = new HashSet<Integer>();


pincodes.add(523302);
pincodes.add(500073);
pincodes.add(500081);

HashMap<String, Integer> wordCount = new HashMap<String,Integer>();


wordCount.put("ratan",5);
wordCount.put("is",2);
wordCount.put("great",5);

Services services = new Services();


services.setNames(names);
services.setPincodes(pincodes);
services.setWordCount(wordCount);

//get the data using getters


services.getNames().forEach(s->System.out.println(s));
services.getPincodes().forEach(i -> System.out.println(i));
services.getWordCount().forEach((k,v)->System.out.println(k+" "+v));
}
}

package com.tcs.cloneserialize;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FilterEx {

public static void main(String[] args) {

List<Integer> values = Arrays.asList(1,2,3,4,5,6,6,4,6);


//values.stream().filter(i->i%2==0).forEach(s->System.out.println(s));

List<Integer> even = values.stream().filter(i->i


%2==0).collect(Collectors.toList());
System.out.println(even);

Set<Integer> seven = values.stream().filter(i->i


%2==0).collect(Collectors.toSet());
System.out.println(seven);
}
}

ex-1:
package com.tcs.cursor;

import java.util.ArrayList;
import java.util.Iterator;

public class ReadingDataEx {

public static void main(String[] args) {


ArrayList<String> objs = new ArrayList<String>();
objs.add("ratan");
objs.add("anu");
objs.add("surekha");
objs.add("sravya");

Iterator itr = objs.iterator();


while(itr.hasNext())
{ String str = (String)itr.next();
System.out.println(str);
}

System.out.println("**********");

Iterator<String> gitr = objs.iterator();


while(gitr.hasNext())
{ String str = gitr.next();
System.out.println(str);
}
System.out.println("*********");
Iterator<String> removeitr = objs.iterator();
while(removeitr.hasNext())
{ String str = removeitr.next();
if(str.startsWith("s"))
removeitr.remove();
}

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;

public class ReadingDataEx5 {

public static void main(String[] args) {

ArrayList<Product> products = new ArrayList<Product>();


products.add(new Product(101, "pen", 12.5));
products.add(new Product(102, "watch", 1244.5));
products.add(new Product(103, "mobile", 378472.5));

System.out.println("****for each loop****");


for(Product p :products)
{ System.out.println(p.pid+" "+p.pcost+" "+p.pname);
}

System.out.println("******get() method*****");
Product product = products.get(2);
System.out.println(product.pid+" "+product.pname+" "+product.pcost);

System.out.println("****Iterator cursor to remove the data***");


Iterator<Product> itr = products.iterator();
while(itr.hasNext())
{ Product p = itr.next();
if(p.pname.equals("watch"))
itr.remove();
}

System.out.println("******ListIterator to read the data*****");


ListIterator<Product> lstr = products.listIterator();
lstr.forEachRemaining(p ->System.out.println(p.pid+" "+p.pname+"
"+p.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.

You might also like