Collection v3

Sunil OS
Sunil OSCorporate Training and Placements
www.SunilOS.com 1
www.sunilos.com
www.raystec.com
Collections Framework
Agenda
Collection List/Set and Map
Iterator and Fail Fast
Why to use
o ArrayList vs LinkedList
o ArrayList vs Vector
o HashMap vs HashTable
o Iterator vs Enumeration
Synchronize Collection
Equals() and HashCode()
www.SunilOS.com 2
Generics
Wrapper Classes
Autoboxing/Unboxing
Concurrent collection
Stream API
www.SunilOS.com 3
Collections Framework
Collection
Set
SortedSet
List Queue
Map
SortedMap
A Map is not a true Collection.
www.SunilOS.com 4
Collections Framework
A collections framework is a unified architecture for
representing and manipulating collections.
It consists of
o Interfaces – Collection, Set, List, Queue
o Concrete Classes – ArrayList, Hashmap, HashSet, etc.
o Algorithm - searching and sorting
www.SunilOS.com 5
Example
SET [1,2,4,5,6,7,8]
LIST [1,2,4,5,7,3,3,4,5]
QUEUE [1,2,4,5,7,3,3,4,5]
MAP [ {1,”ONE”}, {2,”TWO”}, {3,”THREE”} ,
{4,”THREE”}]
www.SunilOS.com 6
Collection Interfaces
Collection-A collection represents a group of objects known as its
elements.
Set - cannot contain duplicate elements.
List- ordered collection, can contain duplicate elements.
Queue - holds multiple elements prior to processing. a Queue
provides additional insertion, extraction, and inspection
operations.
Map - an object that maps keys to values. A Map cannot contain
duplicate keys.
SortedSet - a Set that maintains its elements in ascending order.
SortedMap - a Map that maintains its mappings in ascending key
order.
www.SunilOS.com 7
List by regular array
public static void main(String[] args) {
o String[] names = new String[5];
o for(int i=0;i<names.length; i++){
•names[i]= " No # " + i;
o }
o System.out.println("Names =" + names.length);
}
Disadvantages:
o All elements should be of same type, here it is String.
o Primitive data type arrays can be defined.
o Array size is Fixed. Defined at the time of creation.
www.SunilOS.com 8
List by Collection framework
 public static void main(String[] args) {
o ArrayList names = new ArrayList();
o for(int i=0;i<10; i++){
• names.add(" No # " + i);
o }
o System.out.println("Names =" + names.size());
o Object o = names.get(0);
o String name = (String) o;
o //String name = (String) names.get(0);
o System.out.println(“ First Name is " + name);
 }
Advantages:
o Unlimited size, no need to define array size at the time of creation.
o Add object of any class, in other words any object in Java.
o Add only objects but NOT primitive data types.
www.SunilOS.com 9
Interface Collection
add(o) Add a new element
addAll(c) Add a collection
clear() Remove all elements
contains(o) Membership checking
containsAll(c) Inclusion checking
isEmpty() Whether it is empty
iterator() Return an iterator
remove(o) Remove an element
removeAll(c) Remove a collection
retainAll(c) Keep the elements
size() The number of elements
www.SunilOS.com 10
Interface List
add(i,o) Inserts o at position i.
get(i) Returns the i-th element.
remove(i) Removes the i-th element.
set(i,o) Replaces the i-th element with o.
indexOf(o) Searches object from beginning.
lastIndexOf(o) Searches object from end.
sublist(start index, end index) Returns
sublist.
List allows multiple NULL values to be inserted.
www.SunilOS.com 11
Interface Set
Contains UNIQUE set of values.
Contains at most one NULL value.
Does not declare additional methods.
www.SunilOS.com 12
Interface Queue
 element(): Retrieves, but does not remove the head of this queue.
 offer(E o): Inserts the specified element into this queue, if
possible. Returns true if inserted.
 peek(): Retrieves, but does not remove the head of this queue,
returning null if this queue is empty.
 poll(): Retrieves and removes the head of this queue, or null if this
queue is empty.
 remove(): Retrieves and removes the head of this queue.
Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()
www.SunilOS.com 13
Interface Map
 clear() Removes all mappings.
 containsKey(k) Checks membership of Key.
 containsValue(v) Checks membership of Value.
 entrySet() Set of key-value pairs.
 get(k) Returns the value associated with Key.
 isEmpty() Whether it is empty.
 keySet() Returns Set of keys.
 put(k,v) Inserts Key and Value pair.
 remove(k) Removes the mapping of Key.
 size() Returns size of Map.
 values() Returns the List of values.
www.SunilOS.com 14
Concrete Collections
Interface Set List Map
Impleme-
ntation
HashSet HashMap
ArrayList
TreeSet
(SortedSe
t)
TreeMap
(SortedMap)
LinkedList
Historical Vector Stack Hashtable
Propert
ies
www.SunilOS.com 15
Concrete Collections
HashSet Set hash table
TreeSet SortedSet balanced binary tree
ArrayList List resizable-array
LinkedList List linked list
Vector List resizable-array
HashMap Map hash table
TreeMap SortedMap balanced binary tree
Hashtable Map hash table
www.SunilOS.com 16
ArrayList implements List
 public static void main(String[] args) {
o ArrayList v = new ArrayList();
o v.add(“One");
o v.add(“Two");
o v.add(“Three");
o Integer i = new Integer(4);
o v.add(i);
o Integer value = (Integer) v.get(3);
o System.out.println(“Index#3 value = " +
value);
 }
www.SunilOS.com 17
Vector implements List
public static void main(String[] args) {
o Vector v = new Vector();
o v.add(“One");
o v.add(“Two");
o v.add(“Three");
o Integer i = new Integer(4);
o v.add(i);
o Integer value = (Integer) v.get(3);
o System.out.println(“Index#3 value = " +
value);
}
www.SunilOS.com 18
ArrayList – read all elements
public static void main(String[] args) {
o ArrayList v = new ArrayList();
o v.add(“One");
o …..
o int size = v.size();
o for (int j = 0; j < size; j++) {
o System.out.println(j + " : " +
v.get(j));
o }
An object is converted into string by o.toString() method.
toString() method is defined in Object class.
www.SunilOS.com 19
toString() : converts object into string
System.out.println(j + " : " + v.get(j));
OR
Object o = v.get(j);
System.out.println(j + " : " + o);
OR
Object o = v.get(j);
System.out.println(j + ":" + o.toString());
www.SunilOS.com 20
ArrayList – read all elements
public static void main(String[] args) {
o ArrayList v = new ArrayList();
o v.add("Jay");
o …..
o Iterator it = v.iterator(); //Gets an iterator
o while(it.hasNext())
•Object o = it.next(); //Gets next element
•System.out.println(o);
•//System.out.println(it.next());
o }
}
www.SunilOS.com 21
Interface Iterator
Methods
oboolean hasNext();
oObject next();
ovoid remove();
The iterator() method is defined in the
Collection interface
www.SunilOS.com 22
Iterator
Set s = new TreeSet();
s.add(“123”); ..
Iterator it = s.iterator();
Vector v = new Vector();
v.add(“123”); ..
Iterator it = v.iterator();
www.SunilOS.com 23
Map – Hashtable and HashMap
 public static void main(String[] args) {
o HashMap m = new HashMap();
o m.put("RN1001", 890);
o m.put("RN1002",900);
o m.put("RN1003",780);
o Integer i = (Integer)m.get("RN1002");
o Set keys = m.keySet();
o Collection vals = m.values()
ArrayList vs Linked List
www.SunilOS.com 24
HashMap vs Hashtable
HashMap
Asynchronous.
Not Thread Safe.
Permits NULL values as Key
and Value.
High performance.
Used in single-user
application.
HashTable
Synchronous
Thread Safe
Does not permit NULL
Slow performance
Used in multi-user application.
www.SunilOS.com 25
ArrayList vs Vector
ArrayList
Asynchronous.
Not Thread Safe.
High performance.
Grows by half of its size.
Used in single-user
application.
Vector
Synchronous
Thread Safe
Slow performance
Double the size when grow
Used in multi-user application.
www.SunilOS.com 26
Grows by half of its size Grows by double of its size
+ +
www.SunilOS.com 27
java.util.Enumeration
Vector v = new Vector();
Enumeration e = v.elements()
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
Iterator and Enumeration both are same but Iterator has one
additional method ‘remove()’.
Enumeration can be used with only historical classes Vector,
Hashtable, etc.
Iterator vs Enumeration
Iterator
It is fail-fast.
Can remove an object.
Enumeration
Not fail-fast
Can’t remove an object
Available with historical
classes Vector, HashTable,
Stack, etc.
www.SunilOS.com 28
Fail-fast
If the collection is structurally modified at any time
after the Iterator is created, in any way except through
the Iterator's own remove() method, then Iterator will
throw the following exception:
oConcurrentModificationException.
www.SunilOS.com 29
www.SunilOS.com 30
Instantiate V/AL/HT/HM
 Vector v = new Vector();//Default Capacity 10
 Vector v = new Vector(20);//Initial capacity 20
 Vector v = new Vector(20,15);//Initial capacity 20 and then
increase by 15
 ArrayList al = new ArrayList();//Default Capacity 10
 ArrayList al = new ArrayList(20);//Initial Capacity
 Hashtable ht = new Hashtable();
 Hashtable ht = new Hashtable(20);
 int i = al.capacity();//Returns the current capacity of this
vector
 int s = al.size();//Returns the number of components in this
vector
www.SunilOS.com 31
Synchronize Collection
Non-synchronized collections can be synchronized by
Collections class using following methods:
o Collection c = Collections.synchronizedCollection(c);
o List syncList = Collections.synchronizedList(al);
o Set syncSet = Collections.synchronizedSet(s);
o SortedSet syncSet =
Collections.synchronizedSortedSet(s);
o Map syncMap = Collections.synchronizedMap(m);
o TreeMap syncMap = Collections.synchronizedTreeMap(m);
Method equals() and hashCode()
Both methods are found in Object class.
They play imported role in identification and
searching of elements in Collections.
www.SunilOS.com 32
Marksheet – Search and Remove
 List l = new ArrayList()
 Marksheet m1 = new Marksheet();
 l.add(m1);
 Marksheet m2 = new Marksheet();
 l.add(m2);
 …
 l.contains(m2);//uses equals()
 l.remove(m2);//uses equals()
 …
 HashMap map = new HashMap();
 map.put(m1,”M1”);//use hashCode()
www.SunilOS.com 33
:Marksheet
-rollNo:String
-name : String
-physics :int
-chemistry :int
-maths :int
+getRollNo():String
+setRollNo()
+getPhysics ():int
+setPhysics ()
+getChemistry():int
+setChemistry()
+getMaths():int
+setMaths()
Overriding equals() and hashCode()
equals() is used to search or remove an object in a Collection.
hashCode() returns an integer that uniquely identifies an
object in Hash Collections.
If two objects are equals by equals() method then their hash
code produced by hashCode() method must be same.
If equals() method is overridden then it is recommended to
override hashCode() method to maintain uniqueness on an
object in the collection.
www.SunilOS.com 34
Marksheet: equals() and hashCode()
Here are overridden methods of Marksheet class
 public boolean equals(Object o) {
 if (o == null) return false;
 if (!(o instanceof Marksheet)) return false;
 Marksheet other = (Marksheet) o;
 return this.getRollNo().equals(other.getRollNo());
 }
 public int hashCode() {
 return rollNo.hashCode();
 }
www.SunilOS.com 35
Sorting
Framework provides two interfaces to sort the
collection.
Comparable and Comparator interfaces are used to compare
same type of objects.
Collections.sort() method uses either interface to
sort elements of a collection.
Sortable Class can implement Comparable interface and
provides natural ordering using primary key attribute.
Sortable Class may have multiple Comparators, comparing on
different attributes.
www.SunilOS.com 36
Sorting ( Cont. )
A collection storing objects of Sortable Class, can be sorted by
Collections.sort() method.
// Sorts using Comparable
Collections.sort(c)
// Sorts using Comparator object
Collections.sort(c, comparator)
www.SunilOS.com 37
Comparable Interface
 It does natural ordering.
 It uses primary key to order collection.
 public int compareTo(Marksheet m){
o return rollNo.compareTo(m.rollNo);
 }
 ArrayList marksheets = new
ArrayList();
 marksheets.add(new Marksheet());
 marksheets.add(new Marksheet());
 marksheets.add(new Marksheet());
 Collections.sort(marksheets);
www.SunilOS.com 38
:Marksheet
-rollNo:String
-name : String
-physics :int
…
+compareTo(Marksheet m):int
+getRollNo():String
+setRollNo()
+getPhysics ():int
+setPhysics ()
+getChemistry():int
+setChemistry()
+…..
:Comparable
Comparator Interface
 One class may have multiple
comparators.
 Number of comparators are depending on
number of attributes to be sorted.
 If Marskheets are sorted ascending by
‘name’ attribute then OrderByName
comparator is created.
 If Marskheets are sorted by ascending and
descending by ‘name’ attribute then
OrderByNameAsc and
OrderByNameDesc comparators are
created.
 More attributes are required to be sorted,
create more comparators.
www.SunilOS.com 39
:OrderByName
+compare(Marksheet m1,
Marksheet m2) : int
:Comparator
Comparator Interface ( cont.)
 class OrderByName implements Comparator<Marksheet>{
 public int compare(Marksheet m1,Marksheet m2){
 return m1.getName().compareTo(m2.getName());
 }
 }
 class OrderByMaths implements Comparator<Marksheet>{
 public int compare(Marksheet m1,Marksheet m2){
 return m1.getMaths() - m2.getMaths());
 }
 }
 Collections.sort(marksheets, new OrderByName());
 Collections.sort(marksheets, new OrderByMaths());
www.SunilOS.com 40
Return value ( -ve, 0 , +ve )
Methods compare() and compareTo(), both
return integer value that can be –ve, 0 or +ve.
o -ve indicates current (first) object is smaller than second
one.
o 0 indicates both are equals.
o +ve indicates current (first) object is greater than second
one.
www.SunilOS.com 41
www.SunilOS.com 42
Generics
Generics provides a way in order to communicate the
type of a collection to the compiler.
Defines type of a collection to compiler.
www.SunilOS.com 43
Before Generics
ArrayList l = new ArrayList ();
l.add("One");
l.add("Two");
String str = (String)l.get(1);
System.out.println(str);
Iterator it = l.iterator();
while (it.hasNext()) {
 String val = (String) it.next();
 ..
}
www.SunilOS.com 44
After Generics
ArrayList<String> l = new ArrayList<String>
();
l.add("One");
l.add("Two");
String str = l.get(1);
System.out.println(str);
Iterator<String> it = l.iterator();
while (it.hasNext()) {
 String val = it.next();
 ..
}
www.SunilOS.com 45
Generics
Before
HashMap map = new HashMap ();
map.put(“1”,”One”); //Correct
After
HashMap <String,Integer> map
= new HashMap <String,Integer>();
map.put(“1”,”One”); // Compilation Error
www.SunilOS.com 46
AutoBoxing/UnBoxing
Primitive – Wrapper Class
* byte - Byte
* short - Short
* int - Integer
* long - Long
* float - Float
* double - Double
* char - Character
* boolean - Boolean
www.SunilOS.com 47
Wrapper   Primitive
 double d = 5.5;
 Double dObj = new Double(d);
 double d1 = dObj.doubleValue();
 char c = 'A';
 Char cObj = new Char(c);
 char c1 = cObj.charValue();
 boolean b = true;
 Boolean bObj = new Boolean(b);
 boolean b1 = bObj.booleanValue();
www.SunilOS.com 48
Autoboxing UnBoxing
//Old
int i = 5;
Integer iObj = new Integer(i);
ArrayList l = new ArrayList();
l.add(iObj);
int k = iObj.intValue();
//New Autoboxing/UnBoxing
Integer iObj = i; //Autoboxing
int k = iObj; //UnBoxing
l.add(k); //Autoboxing
Concurrent Collection
www.SunilOS.com 49
Synchronized Collection V/S Concurrent Collection
Synchronized Collections are
slow in performance
Multiple threads can access a
synchronized collection
sequentially. Only one thread
can access the collection at a
time.
Permits null values
Synchronized Collection locks
the entire collection.
Static synchronized methods
of Collections class are used to
make a collection synchronize.
Concurrent Collections are
fast in performance
Multiple threads can access a
concurrent collection
concurrently. Multiple threads
can access the collection at a
time.
It does not permit null values.
Concurrent Collection does
not lock the entire collection,
it does lock only one element
at a time. In other words, each
element has a separate lock.
www.SunilOS.com 50
Concurrent Collection Key Interfaces
BlockingDeque
o LinkedBlockingDeque
o LinkedBlockingQueue
BlockingQueue
o ArrayBlockingQueue
o SynchronousQueue
o PriorityBlockingQueue
ConcurrentMap
o ConcurrentHashMap
ConcurrentNavigableMap
o ConcurrentSkipListMap
TransferQueue
o LinkedTransferQueue
www.SunilOS.com 51
Concurrent Collection
 public class TestHashMap extends Thread {
 private static ConcurrentHashMap<String, Integer> hm =
 new ConcurrentHashMap<String, Integer>();
 public void run() {
 hm.put("Four", 4);
 }
 public static void main(String[] args) {
 hm.put("One", 1);
 hm.put("Two", 2);
 hm.put("Three", 3);
 TestHashMap t1 = new TestHashMap();
 t1.start();
 for (Object o : hm.entrySet()) {
 System.out.println(o);
 }
 System.out.println(hm);
 } www.SunilOS.com 52
Java Stream API
www.SunilOS.com 53
java.util.Stream
Stream is a series of objects.
Source of a stream is an Array, Collection, or Other I/O
source.
Stream does not store data, it does only intermediate
operations.
It can filter and manipulate the elements of its source.
Streams are lazy, the source and intermediate operations do
nothing until objects are needed by the terminal operation.
www.SunilOS.com 54
Steams vs Collection
It does not store data
It is read-only
It can only be read once
Elements can not be directly
accessed
It stores data
It is read and write both
It can be read multiple times
Elements can be directly
accessed
i = list.get(0)
www.SunilOS.com 55
www.SunilOS.com 56
list.stream().map(e ->
e.phone).filter(e -> e.length() ==
10).distinct()
.collect(Collectors.collectingAndThe
n(Collectors.toList(), e -> {
Collections.shuffle(e);
return e.stream();
})).limit(3).forEach(e ->
System.out.println(e));
www.SunilOS.com 57
Intermediate Operations
map() -It maps a function to a stream and changes elements
of the stream
filter() - It filters element of the stream
distinct() - It removes duplicate elements from the stream
sorted() - It sorts elements of the stream
limit() - It limits and returns the stream according to the given
max size parameter
skip() - It skips the given N elements of the stream
www.SunilOS.com 58
Terminal operations
 collect() - It converts an stream into collection
 toArray() - It converts a stream into array
 count() -It returns the count of the elements in the stream
 reduce() - It reduces the elements of the stream according to the given identity value.
 min() - It returns the minimum element of the stream according to the given
comparator
 max() - It returns the maximum element of the stream according to the given
comparator
 anyMatch() - It will return any matched element according to the matched predicate. if
the stream is empty then return false
 allMatch() -It will return all the matched elements from a stream. returns true if the
stream is empty.
 noneMatch() - It returns the matched elements of the predicate. returns true if the
stream is empty
 findAny() - It returns an optional describing some elements of the stream
 findFirst() - It returns the first elements of the stream.
www.SunilOS.com 59
How to create a Stream
List<String> items = Arrays.asList("One",
"Two", "Three", "Three", "Four");
//Create Stream
Stream<String> stream = items.stream();
// Print all elements from stream
stream.forEach(e -> {
System.out.println(e);
});
www.SunilOS.com 60
Some Operations
items.stream().sorted().forEach(e -> {
System.out.println(e);
});
items.stream().map(e ->
e.toUpperCase()).forEach(e -> {
System.out.println(e);
});
items.stream().filter(e ->
e.startsWith("T")).distinct().map(e ->
e.toUpperCase()).sorted().forEach(e -> {
System.out.println(e);
});
www.SunilOS.com 61
Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 62
Thank You!
www.SunilOS.com 63
www.SunilOS.com
1 of 63

Recommended

Java IO Streams V4 by
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
294 views42 slides
Threads V4 by
Threads  V4Threads  V4
Threads V4Sunil OS
319 views37 slides
Exception Handling by
Exception HandlingException Handling
Exception HandlingSunil OS
1.5M views28 slides
Java 8 - CJ by
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
954.1K views17 slides
JDBC by
JDBCJDBC
JDBCSunil OS
458.2K views54 slides
OOP V3.1 by
OOP V3.1OOP V3.1
OOP V3.1Sunil OS
487 views69 slides

More Related Content

What's hot

JavaScript by
JavaScriptJavaScript
JavaScriptSunil OS
519K views27 slides
Java Basics V3 by
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
716 views67 slides
Log4 J by
Log4 JLog4 J
Log4 JSunil OS
441.2K views30 slides
Java Input Output and File Handling by
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
1.1M views45 slides
JAVA OOP by
JAVA OOPJAVA OOP
JAVA OOPSunil OS
1.5M views55 slides
Java Threads and Concurrency by
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
1.1M views53 slides

What's hot(20)

JavaScript by Sunil OS
JavaScriptJavaScript
JavaScript
Sunil OS519K views
Java Basics V3 by Sunil OS
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS716 views
Log4 J by Sunil OS
Log4 JLog4 J
Log4 J
Sunil OS441.2K views
Java Input Output and File Handling by Sunil OS
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS1.1M views
JAVA OOP by Sunil OS
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS1.5M views
Java Threads and Concurrency by Sunil OS
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS1.1M views
Resource Bundle by Sunil OS
Resource BundleResource Bundle
Resource Bundle
Sunil OS506.8K views
Machine learning ( Part 1 ) by Sunil OS
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
Sunil OS616.1K views
Machine learning ( Part 2 ) by Sunil OS
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
Sunil OS571.7K views
JUnit 4 by Sunil OS
JUnit 4JUnit 4
JUnit 4
Sunil OS513.5K views
Python Part 1 by Sunil OS
Python Part 1Python Part 1
Python Part 1
Sunil OS606.3K views
PDBC by Sunil OS
PDBCPDBC
PDBC
Sunil OS277.4K views
Java Basics by Sunil OS
Java BasicsJava Basics
Java Basics
Sunil OS1.5M views
Jsp/Servlet by Sunil OS
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS528K views
JAVA Variables and Operators by Sunil OS
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS1.5M views
C++ by Sunil OS
C++C++
C++
Sunil OS590.8K views
Machine learning ( Part 3 ) by Sunil OS
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
Sunil OS529.2K views
Python part2 v1 by Sunil OS
Python part2 v1Python part2 v1
Python part2 v1
Sunil OS608K views
DJango by Sunil OS
DJangoDJango
DJango
Sunil OS124.5K views
C Basics by Sunil OS
C BasicsC Basics
C Basics
Sunil OS596.4K views

Similar to Collection v3

collections by
collectionscollections
collectionsjaveed_mhd
365 views23 slides
Java ArrayList Tutorial | Edureka by
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
1.1K views23 slides
Array in Java by
Array in JavaArray in Java
Array in JavaShehrevar Davierwala
3K views71 slides
Collection Core Concept by
Collection Core ConceptCollection Core Concept
Collection Core ConceptRays Technologies
13 views17 slides
java set1 program.pdf by
java set1 program.pdfjava set1 program.pdf
java set1 program.pdf722820106121SARANS
3 views11 slides
Java10 Collections and Information by
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
295 views29 slides

Similar to Collection v3(20)

Java ArrayList Tutorial | Edureka by Edureka!
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!1.1K views
Java10 Collections and Information by SoftNutx
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx295 views
collectionframework-141116005344-conversion-gate01.pptx by hemanth248901
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
hemanth2489014 views
Tips and Tricks of Developing .NET Application by Joni
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni 74 views
Collections by sagsharma
CollectionsCollections
Collections
sagsharma178 views
Creating custom views by Mu Chun Wang
Creating custom viewsCreating custom views
Creating custom views
Mu Chun Wang560 views
K is for Kotlin by TechMagic
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic514 views
The Ring programming language version 1.5.3 book - Part 44 of 184 by Mahmoud Samir Fayed
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184 by Mahmoud Samir Fayed
The Ring programming language version 1.5.3 book - Part 54 of 184The Ring programming language version 1.5.3 book - Part 54 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184
Futures e abstração - QCon São Paulo 2015 by Leonardo Borges
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
Leonardo Borges1.6K views
The Ring programming language version 1.10 book - Part 54 of 212 by Mahmoud Samir Fayed
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
Collections - Lists & sets by RatnaJava
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava84 views
The Ring programming language version 1.7 book - Part 48 of 196 by Mahmoud Samir Fayed
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196

More from Sunil OS

OOP v3 by
OOP v3OOP v3
OOP v3Sunil OS
107.9K views56 slides
Threads v3 by
Threads v3Threads v3
Threads v3Sunil OS
104.8K views41 slides
Exception Handling v3 by
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
75K views29 slides
Python Pandas by
Python PandasPython Pandas
Python PandasSunil OS
613.7K views119 slides
Angular 8 by
Angular 8 Angular 8
Angular 8 Sunil OS
531K views93 slides
C# Variables and Operators by
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
494.1K views69 slides

More from Sunil OS(10)

OOP v3 by Sunil OS
OOP v3OOP v3
OOP v3
Sunil OS107.9K views
Threads v3 by Sunil OS
Threads v3Threads v3
Threads v3
Sunil OS104.8K views
Exception Handling v3 by Sunil OS
Exception Handling v3Exception Handling v3
Exception Handling v3
Sunil OS75K views
Python Pandas by Sunil OS
Python PandasPython Pandas
Python Pandas
Sunil OS613.7K views
Angular 8 by Sunil OS
Angular 8 Angular 8
Angular 8
Sunil OS531K views
C# Variables and Operators by Sunil OS
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
Sunil OS494.1K views
C# Basics by Sunil OS
C# BasicsC# Basics
C# Basics
Sunil OS481.5K views
Rays Technologies by Sunil OS
Rays TechnologiesRays Technologies
Rays Technologies
Sunil OS915 views
C++ oop by Sunil OS
C++ oopC++ oop
C++ oop
Sunil OS598.3K views
Java Swing JFC by Sunil OS
Java Swing JFCJava Swing JFC
Java Swing JFC
Sunil OS1M views

Recently uploaded

PRELIMS ANSWER.pptx by
PRELIMS ANSWER.pptxPRELIMS ANSWER.pptx
PRELIMS ANSWER.pptxsouravkrpodder
50 views60 slides
Guess Papers ADC 1, Karachi University by
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi UniversityKhalid Aziz
105 views17 slides
JRN 362 - Lecture Twenty-Two by
JRN 362 - Lecture Twenty-TwoJRN 362 - Lecture Twenty-Two
JRN 362 - Lecture Twenty-TwoRich Hanley
39 views157 slides
Berry country.pdf by
Berry country.pdfBerry country.pdf
Berry country.pdfMariaKenney3
80 views12 slides
BUSINESS ETHICS MODULE 1 UNIT I_A.pdf by
BUSINESS ETHICS MODULE 1 UNIT I_A.pdfBUSINESS ETHICS MODULE 1 UNIT I_A.pdf
BUSINESS ETHICS MODULE 1 UNIT I_A.pdfDr Vijay Vishwakarma
92 views25 slides
Mineral nutrition and Fertilizer use of Cashew by
 Mineral nutrition and Fertilizer use of Cashew Mineral nutrition and Fertilizer use of Cashew
Mineral nutrition and Fertilizer use of CashewAruna Srikantha Jayawardana
58 views107 slides

Recently uploaded(20)

Guess Papers ADC 1, Karachi University by Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz105 views
JRN 362 - Lecture Twenty-Two by Rich Hanley
JRN 362 - Lecture Twenty-TwoJRN 362 - Lecture Twenty-Two
JRN 362 - Lecture Twenty-Two
Rich Hanley39 views
12.5.23 Poverty and Precarity.pptx by mary850239
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptx
mary850239514 views
Career Building in AI - Technologies, Trends and Opportunities by WebStackAcademy
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy47 views
The Future of Micro-credentials: Is Small Really Beautiful? by Mark Brown
The Future of Micro-credentials:  Is Small Really Beautiful?The Future of Micro-credentials:  Is Small Really Beautiful?
The Future of Micro-credentials: Is Small Really Beautiful?
Mark Brown102 views
Introduction to AERO Supply Chain - #BEAERO Trainning program by Guennoun Wajih
Introduction to AERO Supply Chain  - #BEAERO Trainning programIntroduction to AERO Supply Chain  - #BEAERO Trainning program
Introduction to AERO Supply Chain - #BEAERO Trainning program
Guennoun Wajih123 views
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx by Niranjan Chavan
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptxGuidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Niranjan Chavan42 views
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... by Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...

Collection v3

  • 2. Agenda Collection List/Set and Map Iterator and Fail Fast Why to use o ArrayList vs LinkedList o ArrayList vs Vector o HashMap vs HashTable o Iterator vs Enumeration Synchronize Collection Equals() and HashCode() www.SunilOS.com 2 Generics Wrapper Classes Autoboxing/Unboxing Concurrent collection Stream API
  • 3. www.SunilOS.com 3 Collections Framework Collection Set SortedSet List Queue Map SortedMap A Map is not a true Collection.
  • 4. www.SunilOS.com 4 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. It consists of o Interfaces – Collection, Set, List, Queue o Concrete Classes – ArrayList, Hashmap, HashSet, etc. o Algorithm - searching and sorting
  • 5. www.SunilOS.com 5 Example SET [1,2,4,5,6,7,8] LIST [1,2,4,5,7,3,3,4,5] QUEUE [1,2,4,5,7,3,3,4,5] MAP [ {1,”ONE”}, {2,”TWO”}, {3,”THREE”} , {4,”THREE”}]
  • 6. www.SunilOS.com 6 Collection Interfaces Collection-A collection represents a group of objects known as its elements. Set - cannot contain duplicate elements. List- ordered collection, can contain duplicate elements. Queue - holds multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations. Map - an object that maps keys to values. A Map cannot contain duplicate keys. SortedSet - a Set that maintains its elements in ascending order. SortedMap - a Map that maintains its mappings in ascending key order.
  • 7. www.SunilOS.com 7 List by regular array public static void main(String[] args) { o String[] names = new String[5]; o for(int i=0;i<names.length; i++){ •names[i]= " No # " + i; o } o System.out.println("Names =" + names.length); } Disadvantages: o All elements should be of same type, here it is String. o Primitive data type arrays can be defined. o Array size is Fixed. Defined at the time of creation.
  • 8. www.SunilOS.com 8 List by Collection framework  public static void main(String[] args) { o ArrayList names = new ArrayList(); o for(int i=0;i<10; i++){ • names.add(" No # " + i); o } o System.out.println("Names =" + names.size()); o Object o = names.get(0); o String name = (String) o; o //String name = (String) names.get(0); o System.out.println(“ First Name is " + name);  } Advantages: o Unlimited size, no need to define array size at the time of creation. o Add object of any class, in other words any object in Java. o Add only objects but NOT primitive data types.
  • 9. www.SunilOS.com 9 Interface Collection add(o) Add a new element addAll(c) Add a collection clear() Remove all elements contains(o) Membership checking containsAll(c) Inclusion checking isEmpty() Whether it is empty iterator() Return an iterator remove(o) Remove an element removeAll(c) Remove a collection retainAll(c) Keep the elements size() The number of elements
  • 10. www.SunilOS.com 10 Interface List add(i,o) Inserts o at position i. get(i) Returns the i-th element. remove(i) Removes the i-th element. set(i,o) Replaces the i-th element with o. indexOf(o) Searches object from beginning. lastIndexOf(o) Searches object from end. sublist(start index, end index) Returns sublist. List allows multiple NULL values to be inserted.
  • 11. www.SunilOS.com 11 Interface Set Contains UNIQUE set of values. Contains at most one NULL value. Does not declare additional methods.
  • 12. www.SunilOS.com 12 Interface Queue  element(): Retrieves, but does not remove the head of this queue.  offer(E o): Inserts the specified element into this queue, if possible. Returns true if inserted.  peek(): Retrieves, but does not remove the head of this queue, returning null if this queue is empty.  poll(): Retrieves and removes the head of this queue, or null if this queue is empty.  remove(): Retrieves and removes the head of this queue. Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek()
  • 13. www.SunilOS.com 13 Interface Map  clear() Removes all mappings.  containsKey(k) Checks membership of Key.  containsValue(v) Checks membership of Value.  entrySet() Set of key-value pairs.  get(k) Returns the value associated with Key.  isEmpty() Whether it is empty.  keySet() Returns Set of keys.  put(k,v) Inserts Key and Value pair.  remove(k) Removes the mapping of Key.  size() Returns size of Map.  values() Returns the List of values.
  • 14. www.SunilOS.com 14 Concrete Collections Interface Set List Map Impleme- ntation HashSet HashMap ArrayList TreeSet (SortedSe t) TreeMap (SortedMap) LinkedList Historical Vector Stack Hashtable Propert ies
  • 15. www.SunilOS.com 15 Concrete Collections HashSet Set hash table TreeSet SortedSet balanced binary tree ArrayList List resizable-array LinkedList List linked list Vector List resizable-array HashMap Map hash table TreeMap SortedMap balanced binary tree Hashtable Map hash table
  • 16. www.SunilOS.com 16 ArrayList implements List  public static void main(String[] args) { o ArrayList v = new ArrayList(); o v.add(“One"); o v.add(“Two"); o v.add(“Three"); o Integer i = new Integer(4); o v.add(i); o Integer value = (Integer) v.get(3); o System.out.println(“Index#3 value = " + value);  }
  • 17. www.SunilOS.com 17 Vector implements List public static void main(String[] args) { o Vector v = new Vector(); o v.add(“One"); o v.add(“Two"); o v.add(“Three"); o Integer i = new Integer(4); o v.add(i); o Integer value = (Integer) v.get(3); o System.out.println(“Index#3 value = " + value); }
  • 18. www.SunilOS.com 18 ArrayList – read all elements public static void main(String[] args) { o ArrayList v = new ArrayList(); o v.add(“One"); o ….. o int size = v.size(); o for (int j = 0; j < size; j++) { o System.out.println(j + " : " + v.get(j)); o } An object is converted into string by o.toString() method. toString() method is defined in Object class.
  • 19. www.SunilOS.com 19 toString() : converts object into string System.out.println(j + " : " + v.get(j)); OR Object o = v.get(j); System.out.println(j + " : " + o); OR Object o = v.get(j); System.out.println(j + ":" + o.toString());
  • 20. www.SunilOS.com 20 ArrayList – read all elements public static void main(String[] args) { o ArrayList v = new ArrayList(); o v.add("Jay"); o ….. o Iterator it = v.iterator(); //Gets an iterator o while(it.hasNext()) •Object o = it.next(); //Gets next element •System.out.println(o); •//System.out.println(it.next()); o } }
  • 21. www.SunilOS.com 21 Interface Iterator Methods oboolean hasNext(); oObject next(); ovoid remove(); The iterator() method is defined in the Collection interface
  • 22. www.SunilOS.com 22 Iterator Set s = new TreeSet(); s.add(“123”); .. Iterator it = s.iterator(); Vector v = new Vector(); v.add(“123”); .. Iterator it = v.iterator();
  • 23. www.SunilOS.com 23 Map – Hashtable and HashMap  public static void main(String[] args) { o HashMap m = new HashMap(); o m.put("RN1001", 890); o m.put("RN1002",900); o m.put("RN1003",780); o Integer i = (Integer)m.get("RN1002"); o Set keys = m.keySet(); o Collection vals = m.values()
  • 24. ArrayList vs Linked List www.SunilOS.com 24
  • 25. HashMap vs Hashtable HashMap Asynchronous. Not Thread Safe. Permits NULL values as Key and Value. High performance. Used in single-user application. HashTable Synchronous Thread Safe Does not permit NULL Slow performance Used in multi-user application. www.SunilOS.com 25
  • 26. ArrayList vs Vector ArrayList Asynchronous. Not Thread Safe. High performance. Grows by half of its size. Used in single-user application. Vector Synchronous Thread Safe Slow performance Double the size when grow Used in multi-user application. www.SunilOS.com 26 Grows by half of its size Grows by double of its size + +
  • 27. www.SunilOS.com 27 java.util.Enumeration Vector v = new Vector(); Enumeration e = v.elements() while (e.hasMoreElements()) { System.out.println(e.nextElement()); } Iterator and Enumeration both are same but Iterator has one additional method ‘remove()’. Enumeration can be used with only historical classes Vector, Hashtable, etc.
  • 28. Iterator vs Enumeration Iterator It is fail-fast. Can remove an object. Enumeration Not fail-fast Can’t remove an object Available with historical classes Vector, HashTable, Stack, etc. www.SunilOS.com 28
  • 29. Fail-fast If the collection is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove() method, then Iterator will throw the following exception: oConcurrentModificationException. www.SunilOS.com 29
  • 30. www.SunilOS.com 30 Instantiate V/AL/HT/HM  Vector v = new Vector();//Default Capacity 10  Vector v = new Vector(20);//Initial capacity 20  Vector v = new Vector(20,15);//Initial capacity 20 and then increase by 15  ArrayList al = new ArrayList();//Default Capacity 10  ArrayList al = new ArrayList(20);//Initial Capacity  Hashtable ht = new Hashtable();  Hashtable ht = new Hashtable(20);  int i = al.capacity();//Returns the current capacity of this vector  int s = al.size();//Returns the number of components in this vector
  • 31. www.SunilOS.com 31 Synchronize Collection Non-synchronized collections can be synchronized by Collections class using following methods: o Collection c = Collections.synchronizedCollection(c); o List syncList = Collections.synchronizedList(al); o Set syncSet = Collections.synchronizedSet(s); o SortedSet syncSet = Collections.synchronizedSortedSet(s); o Map syncMap = Collections.synchronizedMap(m); o TreeMap syncMap = Collections.synchronizedTreeMap(m);
  • 32. Method equals() and hashCode() Both methods are found in Object class. They play imported role in identification and searching of elements in Collections. www.SunilOS.com 32
  • 33. Marksheet – Search and Remove  List l = new ArrayList()  Marksheet m1 = new Marksheet();  l.add(m1);  Marksheet m2 = new Marksheet();  l.add(m2);  …  l.contains(m2);//uses equals()  l.remove(m2);//uses equals()  …  HashMap map = new HashMap();  map.put(m1,”M1”);//use hashCode() www.SunilOS.com 33 :Marksheet -rollNo:String -name : String -physics :int -chemistry :int -maths :int +getRollNo():String +setRollNo() +getPhysics ():int +setPhysics () +getChemistry():int +setChemistry() +getMaths():int +setMaths()
  • 34. Overriding equals() and hashCode() equals() is used to search or remove an object in a Collection. hashCode() returns an integer that uniquely identifies an object in Hash Collections. If two objects are equals by equals() method then their hash code produced by hashCode() method must be same. If equals() method is overridden then it is recommended to override hashCode() method to maintain uniqueness on an object in the collection. www.SunilOS.com 34
  • 35. Marksheet: equals() and hashCode() Here are overridden methods of Marksheet class  public boolean equals(Object o) {  if (o == null) return false;  if (!(o instanceof Marksheet)) return false;  Marksheet other = (Marksheet) o;  return this.getRollNo().equals(other.getRollNo());  }  public int hashCode() {  return rollNo.hashCode();  } www.SunilOS.com 35
  • 36. Sorting Framework provides two interfaces to sort the collection. Comparable and Comparator interfaces are used to compare same type of objects. Collections.sort() method uses either interface to sort elements of a collection. Sortable Class can implement Comparable interface and provides natural ordering using primary key attribute. Sortable Class may have multiple Comparators, comparing on different attributes. www.SunilOS.com 36
  • 37. Sorting ( Cont. ) A collection storing objects of Sortable Class, can be sorted by Collections.sort() method. // Sorts using Comparable Collections.sort(c) // Sorts using Comparator object Collections.sort(c, comparator) www.SunilOS.com 37
  • 38. Comparable Interface  It does natural ordering.  It uses primary key to order collection.  public int compareTo(Marksheet m){ o return rollNo.compareTo(m.rollNo);  }  ArrayList marksheets = new ArrayList();  marksheets.add(new Marksheet());  marksheets.add(new Marksheet());  marksheets.add(new Marksheet());  Collections.sort(marksheets); www.SunilOS.com 38 :Marksheet -rollNo:String -name : String -physics :int … +compareTo(Marksheet m):int +getRollNo():String +setRollNo() +getPhysics ():int +setPhysics () +getChemistry():int +setChemistry() +….. :Comparable
  • 39. Comparator Interface  One class may have multiple comparators.  Number of comparators are depending on number of attributes to be sorted.  If Marskheets are sorted ascending by ‘name’ attribute then OrderByName comparator is created.  If Marskheets are sorted by ascending and descending by ‘name’ attribute then OrderByNameAsc and OrderByNameDesc comparators are created.  More attributes are required to be sorted, create more comparators. www.SunilOS.com 39 :OrderByName +compare(Marksheet m1, Marksheet m2) : int :Comparator
  • 40. Comparator Interface ( cont.)  class OrderByName implements Comparator<Marksheet>{  public int compare(Marksheet m1,Marksheet m2){  return m1.getName().compareTo(m2.getName());  }  }  class OrderByMaths implements Comparator<Marksheet>{  public int compare(Marksheet m1,Marksheet m2){  return m1.getMaths() - m2.getMaths());  }  }  Collections.sort(marksheets, new OrderByName());  Collections.sort(marksheets, new OrderByMaths()); www.SunilOS.com 40
  • 41. Return value ( -ve, 0 , +ve ) Methods compare() and compareTo(), both return integer value that can be –ve, 0 or +ve. o -ve indicates current (first) object is smaller than second one. o 0 indicates both are equals. o +ve indicates current (first) object is greater than second one. www.SunilOS.com 41
  • 42. www.SunilOS.com 42 Generics Generics provides a way in order to communicate the type of a collection to the compiler. Defines type of a collection to compiler.
  • 43. www.SunilOS.com 43 Before Generics ArrayList l = new ArrayList (); l.add("One"); l.add("Two"); String str = (String)l.get(1); System.out.println(str); Iterator it = l.iterator(); while (it.hasNext()) {  String val = (String) it.next();  .. }
  • 44. www.SunilOS.com 44 After Generics ArrayList<String> l = new ArrayList<String> (); l.add("One"); l.add("Two"); String str = l.get(1); System.out.println(str); Iterator<String> it = l.iterator(); while (it.hasNext()) {  String val = it.next();  .. }
  • 45. www.SunilOS.com 45 Generics Before HashMap map = new HashMap (); map.put(“1”,”One”); //Correct After HashMap <String,Integer> map = new HashMap <String,Integer>(); map.put(“1”,”One”); // Compilation Error
  • 46. www.SunilOS.com 46 AutoBoxing/UnBoxing Primitive – Wrapper Class * byte - Byte * short - Short * int - Integer * long - Long * float - Float * double - Double * char - Character * boolean - Boolean
  • 47. www.SunilOS.com 47 Wrapper   Primitive  double d = 5.5;  Double dObj = new Double(d);  double d1 = dObj.doubleValue();  char c = 'A';  Char cObj = new Char(c);  char c1 = cObj.charValue();  boolean b = true;  Boolean bObj = new Boolean(b);  boolean b1 = bObj.booleanValue();
  • 48. www.SunilOS.com 48 Autoboxing UnBoxing //Old int i = 5; Integer iObj = new Integer(i); ArrayList l = new ArrayList(); l.add(iObj); int k = iObj.intValue(); //New Autoboxing/UnBoxing Integer iObj = i; //Autoboxing int k = iObj; //UnBoxing l.add(k); //Autoboxing
  • 50. Synchronized Collection V/S Concurrent Collection Synchronized Collections are slow in performance Multiple threads can access a synchronized collection sequentially. Only one thread can access the collection at a time. Permits null values Synchronized Collection locks the entire collection. Static synchronized methods of Collections class are used to make a collection synchronize. Concurrent Collections are fast in performance Multiple threads can access a concurrent collection concurrently. Multiple threads can access the collection at a time. It does not permit null values. Concurrent Collection does not lock the entire collection, it does lock only one element at a time. In other words, each element has a separate lock. www.SunilOS.com 50
  • 51. Concurrent Collection Key Interfaces BlockingDeque o LinkedBlockingDeque o LinkedBlockingQueue BlockingQueue o ArrayBlockingQueue o SynchronousQueue o PriorityBlockingQueue ConcurrentMap o ConcurrentHashMap ConcurrentNavigableMap o ConcurrentSkipListMap TransferQueue o LinkedTransferQueue www.SunilOS.com 51
  • 52. Concurrent Collection  public class TestHashMap extends Thread {  private static ConcurrentHashMap<String, Integer> hm =  new ConcurrentHashMap<String, Integer>();  public void run() {  hm.put("Four", 4);  }  public static void main(String[] args) {  hm.put("One", 1);  hm.put("Two", 2);  hm.put("Three", 3);  TestHashMap t1 = new TestHashMap();  t1.start();  for (Object o : hm.entrySet()) {  System.out.println(o);  }  System.out.println(hm);  } www.SunilOS.com 52
  • 54. java.util.Stream Stream is a series of objects. Source of a stream is an Array, Collection, or Other I/O source. Stream does not store data, it does only intermediate operations. It can filter and manipulate the elements of its source. Streams are lazy, the source and intermediate operations do nothing until objects are needed by the terminal operation. www.SunilOS.com 54
  • 55. Steams vs Collection It does not store data It is read-only It can only be read once Elements can not be directly accessed It stores data It is read and write both It can be read multiple times Elements can be directly accessed i = list.get(0) www.SunilOS.com 55
  • 57. list.stream().map(e -> e.phone).filter(e -> e.length() == 10).distinct() .collect(Collectors.collectingAndThe n(Collectors.toList(), e -> { Collections.shuffle(e); return e.stream(); })).limit(3).forEach(e -> System.out.println(e)); www.SunilOS.com 57
  • 58. Intermediate Operations map() -It maps a function to a stream and changes elements of the stream filter() - It filters element of the stream distinct() - It removes duplicate elements from the stream sorted() - It sorts elements of the stream limit() - It limits and returns the stream according to the given max size parameter skip() - It skips the given N elements of the stream www.SunilOS.com 58
  • 59. Terminal operations  collect() - It converts an stream into collection  toArray() - It converts a stream into array  count() -It returns the count of the elements in the stream  reduce() - It reduces the elements of the stream according to the given identity value.  min() - It returns the minimum element of the stream according to the given comparator  max() - It returns the maximum element of the stream according to the given comparator  anyMatch() - It will return any matched element according to the matched predicate. if the stream is empty then return false  allMatch() -It will return all the matched elements from a stream. returns true if the stream is empty.  noneMatch() - It returns the matched elements of the predicate. returns true if the stream is empty  findAny() - It returns an optional describing some elements of the stream  findFirst() - It returns the first elements of the stream. www.SunilOS.com 59
  • 60. How to create a Stream List<String> items = Arrays.asList("One", "Two", "Three", "Three", "Four"); //Create Stream Stream<String> stream = items.stream(); // Print all elements from stream stream.forEach(e -> { System.out.println(e); }); www.SunilOS.com 60
  • 61. Some Operations items.stream().sorted().forEach(e -> { System.out.println(e); }); items.stream().map(e -> e.toUpperCase()).forEach(e -> { System.out.println(e); }); items.stream().filter(e -> e.startsWith("T")).distinct().map(e -> e.toUpperCase()).sorted().forEach(e -> { System.out.println(e); }); www.SunilOS.com 61
  • 62. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 62

Editor's Notes

  1. www.sunilos.com