SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
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/

Weitere ähnliche Inhalte

Was ist angesagt?

Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)Anwar Hasan Shuvo
 
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!
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
 

Was ist angesagt? (20)

Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java collections
Java collectionsJava collections
Java collections
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
07 java collection
07 java collection07 java collection
07 java collection
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
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...
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 

Andere mochten auch

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Equals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorEquals, Hashcode, ToString, Comparable e Comparator
Equals, Hashcode, ToString, Comparable e ComparatorRodrigo Cascarrolho
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionDharmendra Prasad
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 CertificationsGiacomo 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 sem5ashish singh
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programsJames Brotsos
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
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 AnswerTOPS Technologies
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Frameworkguestd8c458
 

Andere mochten auch (19)

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
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
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
 

Ähnlich wie Java Collections Tutorials

Collections and generic class
Collections and generic classCollections and generic class
Collections and generic classifis
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
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
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
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 SpringASG
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 

Ähnlich wie 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
 
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...
 
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
 
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
 

Mehr von 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
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android ProblemsProf. Erwin Globio
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and InstallationProf. Erwin Globio
 

Mehr von 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
 

Kürzlich hochgeladen

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Kürzlich hochgeladen (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

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/