0% found this document useful (0 votes)
8 views44 pages

06 Collection

The document provides an overview of Java Collections, including various interfaces and classes such as Set, List, Queue, and Map, as well as their methods and characteristics. It also covers file input/output operations, detailing byte and character streams, and includes examples of how to read from and write to files. Key distinctions between ArrayList and LinkedList are highlighted, along with the use of TreeSet and TreeMap for storing unique elements in sorted order.

Uploaded by

ndm211005
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)
8 views44 pages

06 Collection

The document provides an overview of Java Collections, including various interfaces and classes such as Set, List, Queue, and Map, as well as their methods and characteristics. It also covers file input/output operations, detailing byte and character streams, and includes examples of how to read from and write to files. Key distinctions between ArrayList and LinkedList are highlighted, along with the use of TreeSet and TreeMap for storing unique elements in sorted order.

Uploaded by

ndm211005
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
You are on page 1/ 44

JAVA TECHNOLOGY

CONCEPT OF COLLECTIONS

Content
❑ Collection
❑ Map

❑ File & IO

1
Collections in Java
• Collections in java are a set of classes and interfaces used to
support operations on sets of objects.
For example : Searching, sorting, adding, editing, deleting,… can be done by Java
Collections.

• Collection provides many interfaces (Set , List , Queue , Deque .


..) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet , LinkedHashSet , TreeSet , HashMap .. ).
– Note: All interfaces and classes are defined in the java.util package.
Collection hierarchy
Collection hierarchy
Interfaces
• Set: is a collection that cannot contain two duplicate values
• List: is an ordered collection. List can contain duplicate elements.
can control exactly where elements are inserted and can access
them by index
• Queue: Is A collection provides additional operations such as
insert, get, and check. Queues can be used as FIFO
• Deque: is a queue but can be used as FIFO and LIFO. All new
elements can be inserted, removed and retrieved at both ends.
• Map: Contains a set of (key, value) mappings. A map cannot
contain duplicate keys. Each key can map to at most one value..
Main Methods
Method Description
public boolean add(Object element) Add an element

public boolean addAll (Collection c) Add elements

public boolean remove(Object element) Remove an element

public boolean removeAll (Collection c) Removes all elements from the specified collection

public boolean retainAll (Collection c) Remove all except the specified collection

public int size() Get the total number of elements in a collection


public void clear() Delete all elements in the Collection
public boolean contains(Object element) Check if an element is in a Collection
Check if a Collection contains all the elements of another
public boolean containsAll(Collection c)
Collection
public Iterator iterator() Returns an iterator.
public Object[] toArray() Convert collection to array
public boolean isEmpty() Check if Collection is empty or not
public boolean equals(Object element) Compare 2 collections
Example collection
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;

public class CreateListDemo {


public static void main(String[] args ) {
List<String> list1 = new ArrayList <String>();
list1.add( "hello" );
list1.add( "java" );
list1.add( "collection" );

System.out.println ( “1. Using iterator" );


Iterator<String> it = list1.iterator();
while ( it.hasNext ()) {
System.out.println ( it.next ());
}
System.out.println ( “2. Using for" );
for (String s : list1 ) {
System.out.println ( s ) ;
}
System.out.println ( “3. Using for with index" );
for ( int i = 0; i < list1.size(); i ++) {
System.out.println ( list1.get( i ));
}}}
ArrayList
• The ArrayList class uses a dynamic array to store
elements.
• Elements can be added/removed at any time. So
it is much more flexible than traditional arrays.
• Located in the java.util package

– Can contain duplicate elements.


– Maintains insertion order.
– Not synchronized.
– Allows random access, slower than LinkedList
ArrayList
// import the ArrayList class
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {

// Create an ArrayList object


ArrayList<String> student = new ArrayList<String>();
student.add(“An");
student.add(“Khang");
student.add(“Thinh");
student.add(“Vuong");
System.out.println(student);
}
}
ArrayList
Methods Description
add (int index, E element) Add element to a position
add (E e) Add to end of list
Appends all elements in the specified set to the end of
addAll(Collection<expand E> c)
the list
addAll (int index, Collection < Append all elements in the specified set to the specified
expand E> c) position
clear () Delete all elements from the list
get(int index) Get the value of the element at index position
isEmpty() Check if the list is empty or not
Returns the index of the last occurrence of the specified
lastIndexOf(Object o)
element, or -1 if the list does not contain this element.
toArray() Returns an array containing all the elements in this
list in the correct order.
contains(Object o) Returns true if the list contains the specified
element
indexOf (Object o) Returns the first position of the specified element

removeAll (Collection <?> c) Remove all elements from the list.


ArrayList
ArrayList
Example: Create Array and convert to ArrayList
Get and Set ArrayList
Sort ArrayList
LinkedList
• Java LinkedList class uses doubly
linked list for storage
• It provides linked list data structure.
It extends AbstractList class and
implements List and Deque
interfaces
• Characteristics:
– Can contain duplicate elements.
– Maintains insertion order.
– Not synchronized.
– Fast because no traversal is required.
– Can be used as a list, stack, or queue.
LinkedList
For example:

Write a program to delete the second element, the first


element, and the last element.
LinkedList
ArrayList & LinkedList
ArrayList LinkedList

1) ArrayList uses a dynamic array to LinkedList uses a doubly linked list to


store elements. store its elements.

2) Working with ArrayList is slow than LinkedList is faster than ArrayList

The LinkedList class can act as both a


3) An ArrayList class can only act as a list and a queue because it
list because it only implements List implements the List and Deque
interfaces
4) ArrayList is better for storing and LinkedList is better for manipulating
accessing data data
ArrayList & LinkedList
TreeSet
• The Java TreeSet class implements the Set
interface which uses a tree for storage.
• It implements the NavigableSet interface.
• Objects of the TreeSet class are stored in
ascending order.
• Java TreeSet class contains only unique
elements
• Java TreeSet class access and retrieval time
is very fast.
• Java TreeSet class does not allow null
elements.
• Not synchronized.
TreeSet
TreeSet
Add element to TreeSet:
TreeSet
Add all elements of another TreeSet to TreeSet:

Write a program to
delete an element
TreeSet
TreeMap

• The Java TreeMap class is an implementation


of a red-black tree.
• It provides an efficient way to store key-value
pairs in sorted order.
• Java TreeMap stores values ​based on keys. It
implements the NavigableMap interface and
extends the AbstractMap class.
• Only unique elements.
• Cannot have null keys but can have multiple
null values.
• Not synchronized.
• Maintains ascending order.
TreeMap
FILE AND IO
Data Stream
• Input is the task of putting data into a program/module (keyboard,
file, other module)
• Output is the task of putting data into another storage/module
(file, screen, printer, other module)
• A stream can be defined as a sequential data sequence, there are 2
data streams:
✓ InputStream: Used to read data from the source
✓ OutputStream: Used to write data to the destination

InputStream OutputStream

source Program Destination


Byte Stream
• Byte stream is used to read/write bytes of data (8 bits)
• FileInputStream and FileOutputStream are the 2 most commonly
used classes

OutputStream class: is an abstract class

Method Description
1) public void write(int)throws is used to write a byte to the current
IOException output stream.
2) public void write(byte[])throws is used to write an array of bytes to the
IOException current output stream.
3) public void flush()throws IOException flush current output stream.
4) public void close()throws IOException used to close the current output stream.
Byte Stream
• Byte stream used to read / write data bytes data (8 bit)
• FileInputStream and FileOutputStream is 2 layers Okay history use
often most through

InputStream class: is an abstract class

Method Description
1. public abstract int read()throws Reads the next byte of data from the input
IOException stream. It returns -1 when the end of the file is
reached.
2. public int available()throws Returns an estimate of the number of bytes
IOException that can be read from the current input
stream.
3. public void close()throws IOException used to close the current input stream.
Byte Stream
import java.io.FileInputStream ;
import java.io.FileOutputStream ; Example: Copy file
import java.io.IOException ;

public class FileCopyDemo {


public static void main(String[] args) throws IOException {
FileInputStream in = null ;
FileOutputStream out = null ;
try {
in = new FileInputStream ("C:\java\ file1.txt");
out = new FileOutputStream ("C:\java\ file2.txt");
int c;
while(( c = in.read ()) != -1) {
out.write (c);
}
} finally { if ( in != null ) { print.close ();
if ( out != null ) { out.close ();}
}
System.out.println ( "Done" );
}
}
Byte Stream
import java.io.BufferedInputStream ; • Copy files using
import java.io.BufferedOutputStream ;
import java.io.FileInputStream ; BufferedInputStream and
import java.io.FileOutputStream ; BufferedOutputStream to
import java.io.IOException ; increase read/write speed
public class FileCopyDemo {
public static void main(String[] args ) throws IOException {
BufferedInputStream print = null ;
BufferedOutputStream out = null ;
try {
print = new BufferedInputStream (
new FileInputStream ("C:\java\file1.txt"));
out = new BufferedOutputStream (
new FileOutputStream ("C:\java\file2.txt"));
int c ;
while ((c = in.read()) != -1) {
out.write (c);
}
} finally { if ( in != null ) { in.close ();}
if ( out != null ) { out.close ();}
}
System.out.println("Copied successfully!");
}}
Close stream automatically using try()

• Classes implementing the Closeable interface can be used with


try() to close themselves (the close() method will be called
automatically when the try block ends)
• All InputStream, OutputStream, Reader, Writer implements the
Closeable interface and can be used with try() Wallet example :
Write again copy file section
Close stream automatically using try()
package stream_demo ;

import java.io.BufferedInputStream ;
import java.io.BufferedOutputStream ;
import java.io.FileInputStream ;
import java.io.FileOutputStream ;
import java.io.IOException ;

public class FileCopyDemo {


public static void main(String[] args ) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(
new FileInputStream ("C:\java\file1.txt"));

BufferedOutputStream out = new BufferedOutputStream (


new FileOutputStream ("C:\java\file2.txt"))){
int c ;
while (( c = in.read () ) != -1) {
out.write ( c );
}}
System.out.println ("Copied successfully!"); }}
Character Stream
• Character stream used to read/write 16 bit unicode
• FileReader and FileWriter are the 2 most commonly used
classes
Character Stream
import java.io.FileReader ;
import java.io.FileWriter ;
import java.io.IOException ;

public class FileCopyDemo {


public static void main(String[] args) throws IOException {
FileReader in = null ;
FileWriter out = null ;

try {
in = new FileReader ( "C:\java\file1.txt" );
out = new FileWriter ( "C:\java\file2.txt" );
int c ;
while (( c = in.read ()) != -1) {
out.write ( c );
}
} finally {
if ( in != null ) { in.close ();}
if ( out != null ) { out.close ();}
}
System.out.println ("Copied successfully!");
}

}
Useing Bytes and Character Streams
Using Byte Stream
• Suitable when processing binary data (such as image files, videos,
etc.)
• Byte Stream reading/writing classes are usually named
…InputStream/…OutputStream

Using Character Stream


• Suitable when processing text files
• Character Stream reading/writing classes are usually named
…Reader/…Writer
• Reading/writing binary files using Character Stream can cause
data corruption
Read data from file into String variable
• History use BufferedReader
import java.io.BufferedReader ;
import java.io.FileReader ;
import java.io.IOException ;

public class BufferedReaderDemo {

public static void main(String[] args ) {


StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader (new FileReader (
"C:\java\file1.txt"))) {

String sCurrentLine ;
while((sCurrentLine = br.readLine()) != null ) {
contentBuilder.append(sCurrentLine).append( "\n" );
}
} catch (IOException e) {
throw new RuntimeException ( e );
}

System.out.println(contentBuilder.toString());
}
}
Read data from file into String variable
• useing Files.readAllBytes

import java.io.IOException ;
import java.nio.file.Files ;
import java.nio.file.Paths ;

public class ReadAllBytesDemo {

public static void main(String[] args ) {


String content = "" ;

try {
byte [] bytes = Files.readAllBytes(Paths.get("C:\java\file1.txt"));
content = new String(bytes);

} catch(IOException e) {
throw new RuntimeException(e);
}
System.out.println(content);
}

}
Write string to file
• Sử dụng FileWriter và BufferedWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class StringToFile2 {


public static void main(String[] args) throws IOException {
String content = “I study\r\n Java \r\n";
String path = "C:\\java\\file2.txt";
FileWriter fw = null;
BufferedWriter bw = null;
try { fw = new FileWriter(path);
bw = new BufferedWriter(fw);
bw.write(content);
} catch (IOException e) {throw new RuntimeException(e);
}
finally {if(bw != null) bw.close();
if(fw != null)
fw.close();
} System.out.println("Done");}
}
Write string to file
• Sử dụng Files.write (Java 7)
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class StringToFile {

public static void main(String[] args) {


String content = “I study\r\n Java \r\n";
String path = "c:\\java\\file2.txt";
try {
Files.write(Paths.get(path),
content.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}}
Write object to file
• Sử dụng ObjectInputStream và ObjectOutputStream
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;

public Student(String id, String name) {


this.id = id; this.name = name;
}
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getName() { return name;}
public void setName(String name) {this.name = name;}
@Override
public String toString() {
return "StudentDemo [id=" + id + ", name=" + name + "]";
}
}
Write object to file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class StudentDemo {


public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student("1", "An"));
students.add(new Student("2", "Binh"));
// serialize
try (ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("C:\\java\\students.dat"))) {
for (Student s : students)
out.writeObject(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
Write object to file
List<Student> inputStudents = new ArrayList<Student>();

// deserialize
// detect end of file using the FileInputStream object
try (FileInputStream fi =
new FileInputStream("C:\\java\\students.dat");
ObjectInputStream in = new ObjectInputStream(fi)) {
while (fi.available() > 0) {
inputStudents.add((Student) in.readObject());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
for (Student s : inputStudents) {
System.out.println(s);
}
}
}

You might also like