SlideShare a Scribd company logo
Java Collections Lectures
http://eglobiotraining.com/
Prof. Erwin M. Globio, MSIT
Experienced Java Developer
Java Collections
A Java collection is a data structure which contains and processes a set of
data. The data stored in the collection is encapsulated and the access to the
data is only possible via predefined methods.
For example if your application saves data in an object of type People, you
can store several People objects in a collection.
While arrays are of a fixed size, collections have a dynamic size, e.g. a
collection can contain a flexible number of objects.
Typical collections are: stacks, queues, deques, lists and trees.
As of Java 5 collections should get parameterized with an object declaration
to enable the compiler to check if objects which are added to the collection
have the correct type. This is based on Generics. Generics allow a type or
method to operate on objects of various types while providing compile-time
type safety.
The following code shows an example how to create a Collection of type List which is
parameterized with <String> to indicate to the Java compiler that only Strings are allowed in this
list. .
package collections;
import java.util.ArrayList;
public class MyArrayList {
public static void main(String[] args) {
// Declare the List concrete type is ArrayList
List<String> var = new ArrayList<String>();
// Add a few Strings to it
var.add("Lars");
var.add("Tom");
// Loop over it and print the result to the console
for (String s : var) {
System.out.println(s);
}
}
}
If you try to put a non String into this list, you would
receive a compiler error.
List is only an interface, a common implementation is the
ArrayList class, hence you need to call new ArrayList().
Important implementations
Map and HashMap
The Map interface defines an object that maps keys to values. A map cannot contain
duplicate keys; each key can map to at most one value.
The HashMap class is an efficient implementation of the Map interface. The
following code demonstrates its usage.
package com.eglobiotraining.java.collections.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapTester {
public static void main(String[] args) {
// Keys are Strings
// Objects are also Strings
Map<String, String> mMap = new HashMap<String, String>();
mMap.put("Android", "Mobile");
mMap.put("Eclipse", "IDE");
mMap.put("Git", "Version control system");
// Output
for (String key : mMap.keySet()) {
System.out.println(key +" "+ mMap.get(key));
}
System.out.println("Changing the data");
// Adding to the map
mMap.put("iPhone", "Created by Apple");
// Delete from map
mMap.remove("Android");
System.out.println("New output:");
// Output
for (String key : mMap.keySet()) {
System.out.println(key +" "+ mMap.get(key));
}
}
}
List, ArrayList and LinkedList
List is the interface which allows to store objects in a resizable
container.
ArrayList is implemented as a resizable array. If more elements
are added to ArrayList than its initial size, its size is increased
dynamically. The elements in an ArrayList can be accessed
directly and efficiently by using the get() and get() methods,
since ArrayList is implemented based on an array.
LinkedList is implemented as a double linked list. Its performance
on add() and remove() is better than the performance of
Arraylist. The get() and get() methods have worse performance
than the ArrayList, as the LinkedList does not provide direct
access.
The following code demonstrates the usage of List and ArrayList.
package com.eglobiotraining.java.collections.list;
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(1);
list.add(4);
list.add(5);
list.add(6);
list.add(6);
for (Integer integer : list) {
System.out.println(integer);
}
}
}
Useful collection methods
The java.util.Collections class provides useful functionalities
for working with collections.
Collections
Method Description
Collections.copy(list, list) Copy a collection to another
Collections.reverse(list) Reverse the order of the list
Collections.shuffle(list) Shuffle the list
Collections.sort(list) Sort the list
Using Collections.sort and Comparator in Java
Sorting a collection in Java is easy, just use the
Collections.sort(Collection) to sort your values. The following
code shows an example for this.
package de.eglobiotraining.algorithms.sort.standardjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple {
public static void main(String[] args) {
List list = new ArrayList();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer);
}
}
}
This is possible because Integer implements the Comparable interface. This
interface defines the method compare which performs pairwise comparison of
the elements and returns -1 if the element is smaller then the compared
element, 0 if it is equal and 1 if it is larger.
If what to sort differently you can define your own implementation based on the
Comparator interface.
package com.eglobiotraining.algorithms.sort.standardjava;
import java.util.Comparator;
public class MyIntComparable implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
package com.eglobiotraining.algorithms.sort.standardjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list, new MyIntComparable());
for (Integer integer : list) {
System.out.println(integer);
}
}
}
Note
For the above you could also have used the
Collection.reverse() method call.
This approach is that you then sort any object by any
attribute or even a combination of attributes. For example if
you have objects of type Person with an attribute income
and dataOfBirth you could define different implementations
of Comparator and sort the objects according to your needs.
Exercise: Use Java Collections
Create a new Java project called
com.vogella.java.collections. Also add a package with the
same name.
Create a Java class called Server with one String attribute
called url.
package com.eglobiotraining.java.collections;
public class Server {
private String url;
}
Create getter and setter methods for this attribute using code generation capabilities of
Eclipse. For this select Source → Generate Getters and Setters from the Eclipse menu.
Create via Eclipse a constructor which gets a url as parameter. For this select Source →
Generate Constructor using Fields... from the Eclipse menu.
Type main in the class body and use code completion (Ctrl+Space) to generate a main
method.
In your main method create a List of type ArrayList and add 3
objects of type Server objects to this list.
public static void main(String[] args) {
List<Server> list = new ArrayList<Server>();
list.add(new Server("http://www.eglobiotraining.com"));
list.add(new Server("http://www.google.com"));
list.add(new Server("http://www.heise.de"));
}
Use code completion to create a foreach loop and write the
toString method to the console. Use code completion based
on syso for that.
Run your program.
Use Eclipse to create a toString method based on the url
parameter and re-run your program again.
Prof. Erwin M. Globio, MSIT
Managing Director of eglobiotraining.com
IT Professor of Far Eastern University
Mobile: 09393741359 | 09323956678
Landline: (02) 428-7127
Email: erwin_globio@yahoo.com
Skype: erwinglobio
Website: http://eglobiotraining.com/

More Related Content

What's hot

Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Java Collections
Java  Collections Java  Collections
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
Ranjith Alappadan
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 

What's hot (20)

Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java collections
Java collectionsJava collections
Java collections
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Generics
GenericsGenerics
Generics
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Presentation1
Presentation1Presentation1
Presentation1
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 

Viewers also liked

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
Equals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorEquals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e Comparator
Rodrigo Cascarrolho
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
Dharmendra Prasad
 
Java: Collections
Java: CollectionsJava: Collections
Java: Collections
Arthur Emanuel
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
Giacomo Veneri
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5
ashish singh
 
java collections
java collectionsjava collections
java collections
javeed_mhd
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
One97 Communications Limited
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
James Brotsos
 
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conferenceJava Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Frameworkguestd8c458
 

Viewers also liked (18)

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Equals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorEquals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e Comparator
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
 
Java: Collections
Java: CollectionsJava: Collections
Java: Collections
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5
 
java collections
java collectionsjava collections
java collections
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java collections
Java collectionsJava collections
Java collections
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
 
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conferenceJava Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Framework
 

Similar to Java Collections Tutorials

Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
ifis
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Collections generic
Collections genericCollections generic
Collections generic
sandhish
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Generics collections
Generics collectionsGenerics collections
Generics collections
Yaswanth Babu Gummadivelli
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
IllllBikkySharmaIlll
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
veerendranath12
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
SURBHI SAROHA
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
SURBHI SAROHA
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
ASG
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 

Similar to Java Collections Tutorials (20)

Collections
CollectionsCollections
Collections
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Collections generic
Collections genericCollections generic
Collections generic
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java.util
Java.utilJava.util
Java.util
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 

More from Prof. Erwin Globio

Embedded System Presentation
Embedded System PresentationEmbedded System Presentation
Embedded System Presentation
Prof. Erwin Globio
 
BSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis GuidelinesBSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis Guidelines
Prof. Erwin Globio
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
Prof. Erwin Globio
 
Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic ConfigurationProf. Erwin Globio
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps DevelopmentProf. Erwin Globio
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development LatestProf. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)Prof. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)Prof. Erwin Globio
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 
Android Fragments
Android FragmentsAndroid Fragments
Android Fragments
Prof. Erwin Globio
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android Problems
Prof. Erwin Globio
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and Installation
Prof. Erwin Globio
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
Prof. Erwin Globio
 
Resource Speaker
Resource SpeakerResource Speaker
Resource Speaker
Prof. Erwin Globio
 

More from Prof. Erwin Globio (20)

Embedded System Presentation
Embedded System PresentationEmbedded System Presentation
Embedded System Presentation
 
BSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis GuidelinesBSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis Guidelines
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Networking Trends
Networking TrendsNetworking Trends
Networking Trends
 
Sq lite presentation
Sq lite presentationSq lite presentation
Sq lite presentation
 
Ethics for IT Professionals
Ethics for IT ProfessionalsEthics for IT Professionals
Ethics for IT Professionals
 
Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic Configuration
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
 
Cloud Computing Latest
Cloud Computing LatestCloud Computing Latest
Cloud Computing Latest
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Android Fragments
Android FragmentsAndroid Fragments
Android Fragments
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android Problems
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and Installation
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
 
Resource Speaker
Resource SpeakerResource Speaker
Resource Speaker
 

Recently uploaded

Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 

Recently uploaded (20)

Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 

Java Collections Tutorials

  • 1. Java Collections Lectures http://eglobiotraining.com/ Prof. Erwin M. Globio, MSIT Experienced Java Developer
  • 2. Java Collections A Java collection is a data structure which contains and processes a set of data. The data stored in the collection is encapsulated and the access to the data is only possible via predefined methods. For example if your application saves data in an object of type People, you can store several People objects in a collection. While arrays are of a fixed size, collections have a dynamic size, e.g. a collection can contain a flexible number of objects. Typical collections are: stacks, queues, deques, lists and trees. As of Java 5 collections should get parameterized with an object declaration to enable the compiler to check if objects which are added to the collection have the correct type. This is based on Generics. Generics allow a type or method to operate on objects of various types while providing compile-time type safety.
  • 3. The following code shows an example how to create a Collection of type List which is parameterized with <String> to indicate to the Java compiler that only Strings are allowed in this list. . package collections; import java.util.ArrayList; public class MyArrayList { public static void main(String[] args) { // Declare the List concrete type is ArrayList List<String> var = new ArrayList<String>(); // Add a few Strings to it var.add("Lars"); var.add("Tom"); // Loop over it and print the result to the console for (String s : var) { System.out.println(s); } } }
  • 4. If you try to put a non String into this list, you would receive a compiler error. List is only an interface, a common implementation is the ArrayList class, hence you need to call new ArrayList().
  • 5. Important implementations Map and HashMap The Map interface defines an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The HashMap class is an efficient implementation of the Map interface. The following code demonstrates its usage. package com.eglobiotraining.java.collections.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapTester { public static void main(String[] args) { // Keys are Strings // Objects are also Strings
  • 6. Map<String, String> mMap = new HashMap<String, String>(); mMap.put("Android", "Mobile"); mMap.put("Eclipse", "IDE"); mMap.put("Git", "Version control system"); // Output for (String key : mMap.keySet()) { System.out.println(key +" "+ mMap.get(key)); } System.out.println("Changing the data"); // Adding to the map mMap.put("iPhone", "Created by Apple"); // Delete from map
  • 7. mMap.remove("Android"); System.out.println("New output:"); // Output for (String key : mMap.keySet()) { System.out.println(key +" "+ mMap.get(key)); } } }
  • 8. List, ArrayList and LinkedList List is the interface which allows to store objects in a resizable container. ArrayList is implemented as a resizable array. If more elements are added to ArrayList than its initial size, its size is increased dynamically. The elements in an ArrayList can be accessed directly and efficiently by using the get() and get() methods, since ArrayList is implemented based on an array. LinkedList is implemented as a double linked list. Its performance on add() and remove() is better than the performance of Arraylist. The get() and get() methods have worse performance than the ArrayList, as the LinkedList does not provide direct access.
  • 9. The following code demonstrates the usage of List and ArrayList. package com.eglobiotraining.java.collections.list; import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(2); list.add(1); list.add(4); list.add(5); list.add(6); list.add(6); for (Integer integer : list) { System.out.println(integer); } } }
  • 10. Useful collection methods The java.util.Collections class provides useful functionalities for working with collections. Collections Method Description Collections.copy(list, list) Copy a collection to another Collections.reverse(list) Reverse the order of the list Collections.shuffle(list) Shuffle the list Collections.sort(list) Sort the list
  • 11. Using Collections.sort and Comparator in Java Sorting a collection in Java is easy, just use the Collections.sort(Collection) to sort your values. The following code shows an example for this. package de.eglobiotraining.algorithms.sort.standardjava; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Simple { public static void main(String[] args) { List list = new ArrayList();
  • 13. This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger. If what to sort differently you can define your own implementation based on the Comparator interface. package com.eglobiotraining.algorithms.sort.standardjava; import java.util.Comparator; public class MyIntComparable implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return (o1>o2 ? -1 : (o1==o2 ? 0 : 1)); } }
  • 14. package com.eglobiotraining.algorithms.sort.standardjava; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Simple2 { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(4); list.add(3); list.add(7); list.add(2); list.add(1); Collections.sort(list, new MyIntComparable()); for (Integer integer : list) { System.out.println(integer); } } }
  • 15. Note For the above you could also have used the Collection.reverse() method call. This approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.
  • 16. Exercise: Use Java Collections Create a new Java project called com.vogella.java.collections. Also add a package with the same name. Create a Java class called Server with one String attribute called url. package com.eglobiotraining.java.collections; public class Server { private String url; }
  • 17. Create getter and setter methods for this attribute using code generation capabilities of Eclipse. For this select Source → Generate Getters and Setters from the Eclipse menu. Create via Eclipse a constructor which gets a url as parameter. For this select Source → Generate Constructor using Fields... from the Eclipse menu. Type main in the class body and use code completion (Ctrl+Space) to generate a main method.
  • 18. In your main method create a List of type ArrayList and add 3 objects of type Server objects to this list. public static void main(String[] args) { List<Server> list = new ArrayList<Server>(); list.add(new Server("http://www.eglobiotraining.com")); list.add(new Server("http://www.google.com")); list.add(new Server("http://www.heise.de")); }
  • 19. Use code completion to create a foreach loop and write the toString method to the console. Use code completion based on syso for that. Run your program. Use Eclipse to create a toString method based on the url parameter and re-run your program again.
  • 20.
  • 21. Prof. Erwin M. Globio, MSIT Managing Director of eglobiotraining.com IT Professor of Far Eastern University Mobile: 09393741359 | 09323956678 Landline: (02) 428-7127 Email: erwin_globio@yahoo.com Skype: erwinglobio Website: http://eglobiotraining.com/