SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
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/

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
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
Java  Collections Java  Collections
Java Collections
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Java collections
Java collectionsJava collections
Java collections
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Generics
GenericsGenerics
Generics
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 

Destaque

Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA 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
Amar Kutwal
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Framework
guestd8c458
 

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

Semelhante a Java Collections Tutorials

Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
phanleson
 

Semelhante a 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
 

Mais de Prof. Erwin Globio

Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic Configuration
Prof. Erwin Globio
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
Prof. Erwin Globio
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
Prof. 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 Programming
Prof. Erwin Globio
 

Mais de 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
 

Último

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
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Último (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
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 ...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
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...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
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...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
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
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

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/