0% found this document useful (0 votes)
3 views38 pages

7 - Java-Collections-Framework - 1 (ArrayList, Collection Sort)

The document provides an overview of the Java Collections Framework, focusing on the List interface and its implementations such as ArrayList, LinkedList, and Vector. It covers key methods for adding, removing, and accessing elements, as well as sorting techniques using Comparable and Comparator interfaces. Additionally, it includes examples demonstrating the use of ArrayList with both primitive types and custom objects.

Uploaded by

leba chinh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views38 pages

7 - Java-Collections-Framework - 1 (ArrayList, Collection Sort)

The document provides an overview of the Java Collections Framework, focusing on the List interface and its implementations such as ArrayList, LinkedList, and Vector. It covers key methods for adding, removing, and accessing elements, as well as sorting techniques using Comparable and Comparator interfaces. Additionally, it includes examples demonstrating the use of ArrayList with both primitive types and custom objects.

Uploaded by

leba chinh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

COLLECTIONS FRAMEWORK
List Interface

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use


Agenda

1 • Overview

2 • List Interface

3 • ArrayList Class

4 • Java Collections Sort

5 • Q&A

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 2


Lesson Objectives
 Understand the hierarchy in the Collections Framework of Java.
 Understand the difference between List and other collection types.
 Perform common operations such as adding, removing, and accessing elements
in an ArrayList.
 Explore sorting techniques for ArrayList elements.
 Discuss the use of Comparator and Comparable interfaces for custom sorting.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 3


Section 1

Overview

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 4


Overview
Collections in Java is a framework that stores and manipulates a
group of objects.

 Collections framework is a hierarchy of interfaces and classes that provides


easy management of a group of objects:
 Interfaces: List, Queue, Deque, Set
 Classes: ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 5


Hierarchy of Collections Framework

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 6


What is a Collection in Java?
A Collection in Java is an object which represents a group of objects,
known as its elements.

 Java Collection vs Collections Framework

Collection in Java Collections Framework


Collection in Java is a class. Collections Framework is a framework.

It is a single unit that contains They are used to manipulate collections.


and manipulates a group of objects.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 7


Methods of Collection interface
 add(E e): It is used to insert an element in this collection.
 addAll(Collection<? extends E> c): It is used to insert the specified collection elements in
the invoking collection.
 remove(Object element): It is used to delete an element from the collection.
 size(): It returns the total number of elements in the collection.
 clear(): It removes the total number of elements from the collection.
 contains(Object element): It is used to search an element.
 toArray(): It converts collection into array.
 isEmpty(): It checks if collection is empty.
 stream(): It returns a sequential Stream with the collection as its source.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 8


Java Collection Cheat Sheet
 Collection Interfaces:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 9


Java Collection

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 10


Section 2

List Interface

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 11


List Interface
The List interface is an ordered collection that allows us to store and
access elements sequentially. It extends the Collection interface.

 Since List is an interface, we cannot create objects from it.


 We can use these classes:
ArrayList

LinkedList

Vector

Stack
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 12
List Interface

 How to use List?


// ArrayList implementation of List
List<String> list1 = new ArrayList<>();
// LinkedList implementation of List
List<String> list2 = new LinkedList<>();

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 13


Methods of List interface
 add() - adds an element to a list
 addAll() - adds all elements of one list to another
 get() - helps to randomly access elements from lists
 iterator() - returns iterator object that can be used to sequentially access elements of lists
 set() - changes elements of lists
 remove() - removes an element from the list
 removeAll() - removes all the elements from the list
 clear() - removes all the elements from the list (more efficient than removeAll())
 size() - returns the length of lists
 toArray() - converts a list into an array
 contains() - returns true if a list contains specified element

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 14


ArrayList
 ArrayList supports dynamic arrays that can grow as needed.
 Array lists are created with an initial size.
 When this size is exceeded, the collection is automatically enlarged.
 When objects are removed, the array may be shrunk

 Syntax:
List<DataType> arrName = new ArrayList<>();

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 15


ArrayList
 ArrayList is implemented as a resizable array. The important points about Java ArrayList
class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index basis.
 In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.
 ArrayList class declaration:

public class ArrayList<E> extends AbstractList<E>


implements List<E>, RandomAccess, Cloneable, Serializable

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 16


Main methods of ArrayList
Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the
collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified collection's iterator.

E get(int index) It is used to fetch the element from the particular position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

boolean contains(Object o) It returns true if the list contains the specified element

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 17


Main methods of ArrayList
Method Description
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

boolean removeIf(Predicate<? super E> filter) It is used to remove all the elements from the list that satisfies the given
predicate.
protected void removeRange(int fromIndex, It is used to remove all the elements lies within the given range.
int toIndex)
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified
collection.
ist<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the given range.

int size() It is used to return the number of elements present in the list.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 18


ArrayList: Adding Elements
 add(Object): This method is used to add an element at the end of the ArrayList.
 add(int index, Object): This method is used to add an element at a specific index in the ArrayList.
public class ListExample {
public static void main(String[] args) {
// Creating an ArrayList of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList Custom inputs
[Link]("Add");
[Link]("elements");
[Link]("an");
[Link]("ArrayList");
// Here we are mentioning the index at which it is to be added
[Link](2, "to");
// Printing all the elements in an ArrayList
[Link](al);

}
}
}

Output
[Add, elements, to, an, ArrayList]

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 19


ArrayList: Changing Elements
public class ArrayListExample {
// Main driver method
public static void main(String args[]) {
// Creating an ArrayList of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList Custom inputs
[Link]("ArrayList");
[Link]("ArrayList");
// Here we are mentioning the index at which it is to be added
[Link](1, "in");
// Printing all the elements in an ArrayList
[Link](al);
// Setting element at 1st index
[Link](2, "Java");
// Printing all the elements in an ArrayList
[Link](al);
}
}

 Output:
[ArrayList, in, ArrayList]
[ArrayList, in, Java]

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 20


ArrayList: Ways to iterate the elements
 There are various ways to traverse the collection elements:
 By for loop.
 By for-each loop.
 By forEach() method.
 By Iterator interface.
 By ListIterator interface.
 By forEachRemaining() method.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 21


ArrayList: Get and Removing Elements
 Can use ArrayList to store String, Number:

Instance of ArrayList

Add value into


ArrayList

Get value from ArrayList

Using for loop to lookup


value

Remove by Value

Remove by Index

Add value by Index

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 22


ArrayList Example
 Iterating the elements using for loop.
Sort statement

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 23


ArrayList with Object
 Create an Animal class:
public class Animal { public void setName(String name) {
private String name; [Link] = name;
private float weight; }

public Animal() { public float getWeight() {


} return weight;
}
public Animal(String name, float weight) {
super(); public void setWeight(float weight) {
[Link] = name; [Link] = weight;
[Link] = weight; };
}
// toString() method
public String getName() { }
return name;
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 24


ArrayList with Object
 Adding elements to ArrayList
 Iterating the elements using for-each loop

public class ArrayListOfObject {


public static void main(String[] args) {
ArrayList<Animal> listOfAnimal = new ArrayList<>(); Instance of ArrayList

[Link](new Animal("Cat", 2.0f));


[Link](new Animal("Dog", 8.0f)); Add Animal to
[Link](new Animal("Turtle", 1.2f)); ArrayList
[Link](new Animal("Bear", 60.0f));
[Link](new Animal("Rabbit", 1.6f));
[Link](new Animal("Bird", 0.6f));

for (Animal animal : listOfAnimal) { Use for-each loop to get


[Link](animal);
}
}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 25


ArrayList with Object
 Iterating ArrayList using Iterator:
Iterator<Animal> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}

 Iterating ArrayList using forEach() method.

[Link](animal -> [Link](animal));

 Output:
Animal [name=Cat, weight=2.0]
Animal [name=Dog, weight=8.0]
Animal [name=Turtle, weight=1.2]
Animal [name=Bear, weight=60.0]
Animal [name=Rabbit, weight=1.6]
Animal [name=Bird, weight=0.6]

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 26


Section 3

Java Collections Sort

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 27


Overview
Collections sort in Java provides in-built methods to sort data faster and in an easier
manner. Collections sort is a method of Java Collections class used to sort a list,
which implements the List interface.

 All the elements in the list must be mutually comparable


 If a list consists of string elements, then it will be sorted in alphabetical order.
 If it consists of a date element, it will be sorted into chronological order.

How does it happen? String and date both implement the Comparable interface in Java. Comparable
implementations provide a natural ordering for a class, which allows the object of that class to be sorted
properly.

ClassCastException: If the list contains elements that are not mutually comparable using the
specified comparator, it will throw ClassCastException.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 28


Collections Sort Method in Java
 The [Link] has two overloaded methods :
public static void sort(List list): Sort the list into ascending order, the
natural ordering of its element.

public static void sort(List list, Comparator c): Sort the list according
to the specified comparator.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 29


Collections Sort Method in Java
 Example:

public class Main {


public static void main(String[] args) {
List<String> studentName = [Link]("Tom","John","Harry","Philip","Max");
[Link](studentName);

for(String name : studentName) {


[Link](name);
}
}
}

 Output:
Harry For objects to have a natural order they must implement the
John interface [Link]. The Comparable interface has a method compareTo():
Max  If both the objects are equal, returns 0
Philip  If the first object is greater than the second, returns a value > 0
Tom  If the second object is greater than the first, returns a value < 0
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 30
Collections Sort Method in Java
 What if we have a list of custom objects: The class must implement a Comparable interface.
 Example:
public class Student implements Comparable<Student> {
private Integer rollno;
private String name;
private String address;
private Double gpa;
// Constructor
public Student(Integer rollno, String name, String address, Double gpa) {
[Link] = rollno;
[Link] = name;
[Link] = address;
[Link] = gpa;
}

// getter and setter methods


// Used to print student details in main()
public String toString() {
return [Link] + " " + [Link] + " " + [Link] + " "+ [Link];
}

@Override
public int compareTo(Student student) {
return [Link]([Link]);
}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 31


Collections Sort Method in Java
 Example: Output:
public class StudentManagement { 23123 Ana Trujillo México D.F. 6.6
public static void main(String[] args) {
22334 Antonio Moreno Berlin 7.7
List<Student> students = new ArrayList<>(); 89346 Christina Berglund London 8.5
12345 Maria Anders Berlin 8.0
Student student1 = new Student(12345, "Maria Anders", "Berlin", 8.0);
Student student2 = new Student(23123, "Ana Trujillo", "México D.F.", 6.6); 74231 Thomas Hardy London 9.2
Student student3 = new Student(22334, "Antonio Moreno", "Berlin", 7.7);
Student student4 = new Student(74231, "Thomas Hardy", "London", 9.2);
Student student5 = new Student(89346, "Christina Berglund", "London", 8.5);

[Link](student1);
[Link](student2);
[Link](student3);
[Link](student4);
[Link](student5);

[Link](students);

[Link](s -> [Link](s));


}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 32


Java Collections sort(List list, Comparator c)
 We can implement the [Link] interface and pass an instance of it as the second
argument of sort().
 Let’s consider that we want to define the ordering based on the “gpa” field of the Student. We
implement the Comparator, and in its compare() method, we need to write the logic for comparison:
public class SortByGpa implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return [Link]().compareTo([Link]());
}
}

 Now, we can sort it using this comparator:


[Link](students, new SortByGpa());
 Output:
23123 Ana Trujillo México D.F. 6.6
22334 Antonio Moreno Berlin 7.7
12345 Maria Anders Berlin 8.0
89346 Christina Berglund London 8.5
74231 Thomas Hardy London 9.2

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 33


Java 8 Lambda : Comparator
 Instead of writing new class for Comparator, using lambda expression, we can provide
sorting logic at runtime as well:

[Link](students, (s1,s2)->{
return [Link]().compareTo([Link]());
});

We will learn more about Lambda Expression and Function Interface in detail in the next session.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 34


Comparator vs Comparable
 The Comparable interface is a good choice to use for defining the default ordering, or
in other words, if it’s the main way of comparing objects.
 So why use a Comparator if we already have Comparable? There are several reasons why:
 Sometimes we can’t modify the source code of the class whose objects we want to sort, thus making
the use of Comparable impossible

 Using Comparators allows us to avoid adding additional code to our domain classes

 We can define multiple different comparison strategies, which isn’t possible when using Comparable

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 35


09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 36
Lesson Summary

1 Overview

2 List Interface

3 ArrayList Class

4 Java Collections Sort

5 Q&A

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 37


THANK YOU!

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use

You might also like