SlideShare a Scribd company logo
Java/J2EE Programming Training
Collections – Sorting, Comparing
Page 2Classification: Restricted
Agenda
• Recap of Arrays, ArrayLists
• Basically, there can be 2 operations that you would want to perform on
Arrays/ArrayLists.. (and maybe, other collections)
• Search: Override equals() and hashCode().
• Sort: provide comparison logic – Two ways
• Comparable interface
• Comparator interface
Comparable vs Comparator Interfaces
Classification: Restricted Page 2
Comparable Interface Example
Classification: Restricted Page 3
public class Person implements Comparable {
private int person_id;
private String name;
/**
* Compare current person with specified person
* return zero if person_id for both person is same
* return negative if current person_id is less than specified one
* return positive if specified person_id is greater than specified
one
*/
@Overrid
e
public int compareTo(Object o) {
Person p = (Person) o;
return this.person_id - o.person_id ;
}
….
}
Comparator Interface
Classification: Restricted Page 4
/**
* Comparator implementation which sorts Person objects on person_id
field
*/
public class SortByPerson_ID implements Comparator{
public int compare(Object o1, Object o2) {
Person p1 = (Person) o;
Person p2 = (Person) o;
return p1.getPersonId() - p2.getPersonId();
}
}
Comparing in Java – Strings and Dates
Classification: Restricted Page 5
• Strings are immutable
• String implements Comparable interface
• Call String1.compareTo(String2)
• Date also implements Comparable.
• Date1.compareTo(Date2)
Where is the Comparator or Comparable interfaces used?
Classification: Restricted Page 6
Exercise…
Classification: Restricted Page 7
1. Create an employee class with fields – id, name, age, salary.
2. Provide default comparison logic for id using java.lang.Comparable
interface.
3. Provide the following comparison logic using java.util.Comparator
interface
• Name
• Age
• Salary
•Name and then Age.
4. Test the above using
• Array of Employees and using Arrays.sort()
• ArrayList of Employees and using Collections.sort()
Thank You

More Related Content

PPTX
Object oriented database
PPTX
Session 16 - Collections - Sorting, Comparing Basics
PPSX
Collections - Sorting, Comparing Basics
DOCX
Smali语法
PPTX
Object oriented database concepts
PPTX
Data types in c++
PDF
New open document text (2)
PPTX
Structures in c language
Object oriented database
Session 16 - Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
Smali语法
Object oriented database concepts
Data types in c++
New open document text (2)
Structures in c language

What's hot (20)

PPTX
Data Types
PPTX
C programing -Structure
PPTX
Structure in c language
PDF
Structures in c++
PPTX
Object database standards, languages and design
PDF
Lecture 07 Data Structures - Basic Sorting
PPTX
Session 17 - Collections - Lists, Sets
PPTX
Basic Data Types in C++
PPTX
Structure in C language
PPTX
Computer data type and Terminologies
PDF
Lecture-05-DSA
PPTX
Encapsulation of operations, methods & persistence
PPT
C Omega
PDF
Duplicate Detection in Hierarchical Data Using XPath
PPT
Patni Hibernate
PPT
PDF
PDF
PDF
Lecture18 structurein c.ppt
Data Types
C programing -Structure
Structure in c language
Structures in c++
Object database standards, languages and design
Lecture 07 Data Structures - Basic Sorting
Session 17 - Collections - Lists, Sets
Basic Data Types in C++
Structure in C language
Computer data type and Terminologies
Lecture-05-DSA
Encapsulation of operations, methods & persistence
C Omega
Duplicate Detection in Hierarchical Data Using XPath
Patni Hibernate
Lecture18 structurein c.ppt
Ad

Similar to Collections - Sorting, Comparing Basics (20)

PDF
Lesson 2.2 abstraction
PPT
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
PPTX
Java Collection
PPTX
Dependency Injection in Spring
 
PPT
Oops concepts in php
PPT
Algorithms Binary Search recursion ppt BSIT
PPTX
Object Class
PPTX
Compose 3rd session.pptx
PPTX
Lecture 5
PDF
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
PPTX
03 object-classes-pbl-4-slots
PPTX
03 object-classes-pbl-4-slots
PPTX
Chapter 3
PPT
C++ classes tutorials
PPTX
Ch.03 - Class Diagram_1 OBJECT ORIENTED ANALYSIS AND DESIGN [O] .pptx
PDF
Unit-3.pptx.pdf java api knowledge apiii
PPT
Classes in C++ computer language presentation.ppt
PPTX
Class and object
PPTX
Overview of Java
PDF
C# / Java Language Comparison
Lesson 2.2 abstraction
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Java Collection
Dependency Injection in Spring
 
Oops concepts in php
Algorithms Binary Search recursion ppt BSIT
Object Class
Compose 3rd session.pptx
Lecture 5
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
Chapter 3
C++ classes tutorials
Ch.03 - Class Diagram_1 OBJECT ORIENTED ANALYSIS AND DESIGN [O] .pptx
Unit-3.pptx.pdf java api knowledge apiii
Classes in C++ computer language presentation.ppt
Class and object
Overview of Java
C# / Java Language Comparison
Ad

More from RatnaJava (13)

PPTX
Review Session and Attending Java Interviews
PPTX
Collections - Lists & sets
PPTX
Collections Array list
PPTX
Exception Handling
PPTX
OOPs with Java - Packaging and Access Modifiers
PPTX
OOP with Java - Abstract Classes and Interfaces
PPTX
OOP with Java - Part 3
PPTX
OOP with Java - continued
PPTX
Object Oriented Programming
PPTX
Data Handling and Function
PPTX
Introduction to Java Part-3
PPTX
Introduction to Java Part-2
PPTX
Introduction to Java
Review Session and Attending Java Interviews
Collections - Lists & sets
Collections Array list
Exception Handling
OOPs with Java - Packaging and Access Modifiers
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Part 3
OOP with Java - continued
Object Oriented Programming
Data Handling and Function
Introduction to Java Part-3
Introduction to Java Part-2
Introduction to Java

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Empathic Computing: Creating Shared Understanding
PDF
Electronic commerce courselecture one. Pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Encapsulation_ Review paper, used for researhc scholars
Mobile App Security Testing_ A Comprehensive Guide.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Review of recent advances in non-invasive hemoglobin estimation
Spectral efficient network and resource selection model in 5G networks
Programs and apps: productivity, graphics, security and other tools
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Empathic Computing: Creating Shared Understanding
Electronic commerce courselecture one. Pdf
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Agricultural_Statistics_at_a_Glance_2022_0.pdf

Collections - Sorting, Comparing Basics

  • 2. Page 2Classification: Restricted Agenda • Recap of Arrays, ArrayLists • Basically, there can be 2 operations that you would want to perform on Arrays/ArrayLists.. (and maybe, other collections) • Search: Override equals() and hashCode(). • Sort: provide comparison logic – Two ways • Comparable interface • Comparator interface
  • 3. Comparable vs Comparator Interfaces Classification: Restricted Page 2
  • 4. Comparable Interface Example Classification: Restricted Page 3 public class Person implements Comparable { private int person_id; private String name; /** * Compare current person with specified person * return zero if person_id for both person is same * return negative if current person_id is less than specified one * return positive if specified person_id is greater than specified one */ @Overrid e public int compareTo(Object o) { Person p = (Person) o; return this.person_id - o.person_id ; } …. }
  • 5. Comparator Interface Classification: Restricted Page 4 /** * Comparator implementation which sorts Person objects on person_id field */ public class SortByPerson_ID implements Comparator{ public int compare(Object o1, Object o2) { Person p1 = (Person) o; Person p2 = (Person) o; return p1.getPersonId() - p2.getPersonId(); } }
  • 6. Comparing in Java – Strings and Dates Classification: Restricted Page 5 • Strings are immutable • String implements Comparable interface • Call String1.compareTo(String2) • Date also implements Comparable. • Date1.compareTo(Date2)
  • 7. Where is the Comparator or Comparable interfaces used? Classification: Restricted Page 6
  • 8. Exercise… Classification: Restricted Page 7 1. Create an employee class with fields – id, name, age, salary. 2. Provide default comparison logic for id using java.lang.Comparable interface. 3. Provide the following comparison logic using java.util.Comparator interface • Name • Age • Salary •Name and then Age. 4. Test the above using • Array of Employees and using Arrays.sort() • ArrayList of Employees and using Collections.sort()