You are on page 1of 47

Kiu d liu Collections

Bi 9 - Kiu d liu Collection

Ni dung
Kiu Collections Giao din

Thc thi
Cc thut ton Lp vt cha Set v Map

Bi 9 - Kiu d liu Collection

Kiu Collections
Mt collection, hay cn gi l container, l mt i tng dng nhm

nhiu phn t trong mt n v duy nht.


Cc collection c s dng lu tr, truy xut v thao tc d liu. V d: mt tp hp cc qun bi, cc th mc th, mt danh b in

thoi,

http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

Bi 9 - Kiu d liu Collection

Collection framework
Mt collection framework l mt kin trc thng nht

biu din v thao tc vi cc d liu kiu collection.


Ba thnh phn ca mt collection framework: Giao din: cc kiu d liu tru tng dng biu

din cc collection.
Thc thi: cc thc thi c th ca cc giao din ca

collection.
Thut ton: Cc phng thc h tr nh sp xp, tm

Bi 9 - Kiu d liu Collection

kim, cc i tng thc thi cc giao din ca collection.

Java collection framework


Lm gim cng vic lp trnh, Tng tc v cht lng chng trnh,

Cho php kh nng tng tc gia cc API khng lin quan,


Lm gim cng sc tm hiu v s dng cc API mi, Lm gim vic thit k cc API mi, Thc y ti s dng phn mm.

Bi 9 - Kiu d liu Collection

Ni dung
Kiu Collections Giao din

Thc thi
Cc thut ton Lp vt cha Set v Map

Bi 9 - Kiu d liu Collection

Giao din
Cc giao din li ca collection ng gi nhiu kiu khc nhau ca

collection. Cc giao din ny cho php cc collection c thao tc mt cch c lp vi cc thc thi ca chng.
Collection Map

Set

List

Queue SortedMap

SortedSet

Bi 9 - Kiu d liu Collection

Giao din
Tt c cc giao din ca Java collection framework l:

public interface Collection<E>


Chng ta nn xc nh kiu E ca cc i tng cha trong collection.
E c th l mt trong cc kiu i tng: Integer, Double, String Object

Bi 9 - Kiu d liu Collection

Duyt collection
Hai cch duyt qua collection: Bng cu trc foreach

Bng cc i tng Iterator


Cu trc foreach for (Object o : collection)

do something
Cc i tng Iterator Collection<E> c; Iterator<E> iter = c.iterator(); while (iter.hasNext()) { E e = iter.next(); ...} Bi 9 - Kiu d liu Collection

Ni dung
Kiu Collections Giao din

Thc thi
Cc thut ton Lp vt cha Set v Map

10

Bi 9 - Kiu d liu Collection

Thc thi
Cc thc thi thng dng ca collection HashSet, TreeSet

ArrayList, LinkedList
PriorityQueue HashMap, TreeMap Bn nn c ti liu v cc lp ny trong API Documentation ny bit

y cc chc nng ca chng.


Packages: java.util.*
11
Bi 9 - Kiu d liu Collection

V d: List
// create a list of odd numbers List<Integer> odds = new ArrayList<Integer>(); for (int i = 1; i < 50; i = i + 2) { odds.add(i); } // print the list: first way for (Integer i : odds) { System.out.println(i); } // print the list: second way Iterator<Integer> iter = odds.iterator(); int i; while (iter.hasNext()) { i = iter.next(); System.out.println(i); } // print the list: third way for (int j = 0; j < odds.size(); j++) { i = odds.get(j); System.out.println(i); Bi 9 - Kiu d liu Collection }

12

Ni dung
Kiu Collections Giao din

Thc thi
Cc thut ton Lp vt cha Set v Map

13

Bi 9 - Kiu d liu Collection

Cc thut ton
Cc thut ton a hnh trong Collection framework ca Java c

th ti s dng.
Tt c cc thut ton u c vit di dng phng thc

tnh.
i s u tin lun l Collection hot ng.

Nhiu thut ton lm vic trn danh sch.

14

Bi 9 - Kiu d liu Collection

Cc thut ton
Cc thut ton gm:
Sp xp Xo trn X l d liu thng xuyn Tm kim

Hp nht
Vic tm kim cc gi tr cc i

15

Bi 9 - Kiu d liu Collection

Sp xp
Cc thut ton sp xp sp xp li danh sch cc phn t

ca n tng dn theo mt quan h th t no .


Cc th t t nhin:
Xu k t S K t Ngy thng i tng ?

16

Bi 9 - Kiu d liu Collection

Sp xp
Giao din Comparable quy nh quan h th t cho mt lp. Cc i tng ca mt lp c th c sp xp t ng nu

lp thc thi giao din Comparable.


Cc lp quan trng ca Java platform m thc thi giao din

Comparable bao gm:


Boolean, Byte, Character, Short, Integer, Long, Float, Double,

BigInteger, BigDouble.
String, Data, File, CollationKey

17

Bi 9 - Kiu d liu Collection

Sp xp
Nu ta c gng sp xp mt danh sch m cc phn t ca n

khng thc thi Comparable, phng thc sp xp s nm mt i tng thuc lp ClassCastException.


Giao din Comparable:
public interface Comparable<T> { public int compareTo(T o); }

Tr li mt gi tr ln hn, nh hn hay bng 0 ty thuc i tng ang xt ln hn, nh hn hay bng vi i tng c so snh.
18
Bi 9 - Kiu d liu Collection

Sp xp
Example: Name.java, NameSort.java
public class NameSort { public static void main(String[] args) { Name nameArray[] = { new Name("John", "Smith"), new Name("Karl", "Ng"), new Name("Jeff", "Smith"), new Name("Tom", "Rich") }; List<Name> names = Arrays.asList(nameArray); Collections.sort(names); System.out.println(names); } }
19
Bi 9 - Kiu d liu Collection

Sp xp
Nu cc i tng m chng ta cn phi sp xp khng thc thi

Comparable, chng ta c th quy nh mt Comparator c dng sp xp.


Giao din Comparator:
public interface Comparator<T> { int compare(T o1, T o2); }

20

Bi 9 - Kiu d liu Collection

Sp xp
Gi s ta c mt lp Employee nh sau:
public class Employee implements public Name name() public int number() { ... { ...

public Date hireDate() { ... ... }

21

Bi 9 - Kiu d liu Collection

Sp xp
ng nhin, chng ti c th sp xp danh sch cc nhn

vin theo tn ca h.
Nu cn chng ta cng c th sp xp danh sch ny theo th

t v thm nin?

22

Bi 9 - Kiu d liu Collection

Sp xp
public class EmpSort { static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() { public int compare(Employee e1, Employee e2) { int dateCmp = e2.hireDate().compareTo(e1.hireDate()); if (dateCmp != 0) return dateCmp; return (e1.number() < e2.number() ? -1 : (e1.number() == e2.number() ? 0 : 1)); } Ta so snh cc gi tr numbers khi m hai gi }; tr ngy thng bng nhau // Employee database static final Collection<Employee> employees = ... ; public static void main(String[] args) { List<Employee> e = new ArrayList<Employee>(employees); Collections.sort(e, SENIORITY_ORDER); System.out.println(e); } }
Bi 9 - Kiu d liu Collection

23

Xo trn
Thut ton xo trn l ngc li ca thut ton sp xp
Sp xp li mt danh sch da trn u vo t mt ngun ngu

nhin m tt c cc hon v c th xy ra vi kh nng ngang nhau.


Rt hu ch trong vic thc hin cc tr chi may ri (th, xc sc

...)

24

Bi 9 - Kiu d liu Collection

Xo trn
public class Shuffle { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for (String a : args) list.add(a); Collections.shuffle(list, new Random()); System.out.println(list); } }

public class Shuffle { public static void main(String[] args){ List<String> list = Arrays.asList(args); Collections.shuffle(list); System.out.println(list); Dng mt ngun ngu } nhin mc nh. }
25
Bi 9 - Kiu d liu Collection

Thao tc d liu
Collection cung cp 5 thut ton thc hin cc thao tc d

liu trn cc i tng ca lp List:


reverse fill copy swap addAll

26

Bi 9 - Kiu d liu Collection

Tm kim
Thut ton binarySearch tm kim mt phn t trong

mt danh sch c sp xp.


Nu phn t c tm thy, ch s ca n c tr li,

nu khng mt gi tr ch s m c tr li.
Hai dng ca thut ton:
Cho mt danh sch v mt phn t tm kim; Cho mt danh sch, mt phn t tm kim v mt

Comparator.

27

Bi 9 - Kiu d liu Collection

Hp nht
Thut ton v tn sut:
m s ln xut hin ca mt phn t trong mt collection.

Thut ton xc nh tp ri nhau


Xc nh xem hai collection cc tch ri nhau khng.

28

Bi 9 - Kiu d liu Collection

Tm cc i
Gi tr cc i:
min ca mt collection max ca mt collection

Hai dng:
Cho mt Collection Cho mt Collection v mt Comparator

c cc ti liu JDK API xem cc thut ton v cc

v d c th.
29
Bi 9 - Kiu d liu Collection

Example: Sort an Array


String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); }

30

Bi 9 - Kiu d liu Collection

Example: Sort an ArrayList


List<String> fruits = new ArrayList<String>(); fruits.add("Pineapple"); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Banana"); Collections.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); }

31

Bi 9 - Kiu d liu Collection

Sort an Object with Comparable


public class Fruit{ private String fruitName; private int quantity; public Fruit(String fruitName, int quantity) { this.fruitName = fruitName; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; }

32

Bi 9 - Kiu d liu Collection

Sort an Object with Comparable


public class SortFruitObject{ static void showList(Fruit[] fruits){ int i=0; for(Fruit temp: fruits){ System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity : " + temp.getQuantity()); } } public static void main(String args[]){ Fruit[] fruits = new Fruit[4];

Fruit pineappale = new Fruit apple = new Fruit("Apple",100); Fruit orange = new Fruit("Orange",80); fruits[0]=pineappale; fruits[1]=apple; fruits[2]=orange; Arrays.sort(fruits); showList(fruits); } } 33} Bi 9 - Kiu d liu Collection

Fruit cannot be cast to Fruit("Pineapple",70); java.lang.Comparable

Sort an Object with Comparable


public class Fruit implements Comparable<Fruit> { private String fruitName; private int quantity; public Fruit(String fruitName, int quantity) { public String getFruitName() { public void setFruitName(String fruitName) { public int getQuantity() { public void setQuantity(int quantity) { //override the compareTo() method public int compareTo(Fruit compareFruit) {

int compareQuantity = ((Fruit) compareFruit).getQuantity();


return this.quantity - compareQuantity; } }

34

Bi 9 - Kiu d liu Collection

Sort an Object with Comparator


public class Fruit implements Comparable<Fruit> { private String fruitName; private int quantity; public Fruit(String fruitName, int quantity) { public String getFruitName() { public void setFruitName(String fruitName) { public int getQuantity() { public void setQuantity(int quantity) { public int compareTo(Fruit compareFruit) { public static Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>() { public int compare(Fruit fruit1, Fruit fruit2) { String fruitName1 = fruit1.getFruitName().toUpperCase(); String fruitName2 = fruit2.getFruitName().toUpperCase(); return fruitName1.compareTo(fruitName2);

}
}; }

35

Bi 9 - Kiu d liu Collection

Sort an Object with Comparator


public class SortFruitObject{ static void showList(Fruit[] fruits){ int i=0; for(Fruit temp: fruits){ System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity : " + temp.getQuantity()); } } public static void main(String args[]){ Fruit[] fruits = new Fruit[4]; Fruit pineappale = new Fruit("Pineapple",70); Fruit apple = new Fruit("Apple",100); Fruit orange = new Fruit("Orange",80); fruits 1 : Pineapple, Quantity : 70 fruits[0]=pineappale; fruits[1]=apple; fruits[2]=orange; Arrays.sort(fruits); showList(fruits);

fruits 2 : Orange, Quantity : 80 fruits 3 : Apple, Quantity : 100

fruits 1 : Apple, Quantity : 100 fruits 2 : Orange, Quantity : 80 fruits 3 : Pineapple, Quantity : 70

36
}

Arrays.sort(fruits, Fruit.FruitNameComparator); Bi 9showList(fruits;) - Kiu d liu Collection }

Ni dung
Kiu Collections Giao din

Thc thi
Cc thut ton Lp vt cha Set v Map

37

Bi 9 - Kiu d liu Collection

Tm cc ch trong vn bn
Cc ch (token, word) l mt dy k t lin nhau, ngn cch bi k t

trng.
V d:
Dng Tom likes Jerry gm 3 ch: Tom, likes, Jerry. Dng Hc sinh hc sinh hc gm 5 ch:
C 3 ch khc nhau l Hc, sinh, hc.
Nu khng phn bit hoa thng th ch c 2 ch khc nhau.

38

Bi 9 - Kiu d liu Collection

Tm cc ch trong vn bn
Cho trc mt tp vn bn ting Anh hoc ting Vit, ta xt hai bi ton

sau:
Lit k cc ch khc nhau trong vn bn m tn s cc ch khc nhau trong vn bn

39

Bi 9 - Kiu d liu Collection

Tm cc ch trong vn bn
gii bi ton 1, ta dng kiu vt cha tp hp:
Giao din Set Ci t ca Set l HashSet

gii bi ton 2, ta dng kiu vt cha nh x:


Giao din Map

Ci t ca Map l HashMap

40

Bi 9 - Kiu d liu Collection

Cc giao din trong th vin


Th vin cc lp vt cha c nhiu giao din cho php thao tc vi nhiu

kiu d liu thng dng:


Set, Map, List, Queue
Collection Map

Set

List

Queue SortedMap

SortedSet

41

Bi 9 - Kiu d liu Collection

c tp vn bn
Reader reader = null; BufferedReader bufferedReader = null; try { // open a reader using UTF-8 encoding so that we can // read Vietnamese text reader = new InputStreamReader(new S dng bng m UTF-8 FileInputStream(fileName), "UTF-8"); c tp bufferedReader = new BufferedReader(reader);

42

Bi 9 - Kiu d liu Collection

c tp vn bn
String line = null; // read the input file, line by line while ((line = bufferedReader.readLine()) != null) { // split the line into tokens String[] tokens = line.split(Constants.DELIMITERS); // add tokens to the set for (String token : tokens) { tokenSet.add(token); Biu thc chnh quy ch nh cc k t } trng, du phy, du chm, m ngoc, }

ng ngoc

public static final String DELIMITERS = "[\\s,\\.\\(\\)]+";

43

Bi 9 - Kiu d liu Collection

S dng Set
private Set<String> tokenSet; tokenSet = new HashSet<String>(); public void print() { System.out.println("There are " + tokenSet.size() + " different tokens."); for (String token : tokenSet) { System.out.println(token); } }

Nu thay HashSet bng TreeSet th ta c tp c sp xp theo th t t nhin ca phn t

Cc phn t l String s c sp theo th t t in

44

Bi 9 - Kiu d liu Collection

S dng Map

Mi nh x c cp phn t: Key Value Trong bi ton 2, Key l token, Value l mt s nguyn m s ln token xut hin Key, Value u phi l cc ki u i tng (khng th l kiu d liu c s)

Key = String Value = Integer

private Map<String, Integer> tokenCounter; tokenCounter = new HashMap<String, Integer>();

45

Bi 9 - Kiu d liu Collection

S dng Map
// add tokens to the counter for (String token : tokens) { Integer count = tokenCounter.get(token); if (count != null) { tokenCounter.put(token, count + 1); } else { tokenCounter.put(token, 1); } }

S dng phng thc get(Key) ly Value gn vi Key.

Nu khng c Key th hm get tr v null

Java 5+ t ng chuyn i gia i v new Integer(i) vi i l mt s nguyn


Bi 9 - Kiu d liu Collection

46

S dng Map
/** * Prints the token counter to the standard console. */ public void print() { System.out.println("There are " + tokenCounter.keySet().size() + " different tokens."); for (String token : tokenCounter.keySet()) { System.out.println(token + " --> " + tokenCounter.get(token)); } }

Nu thay HashMap bng TreeMap th tp kha c sp xp theo th t t nhin.

47

Bi 9 - Kiu d liu Collection

You might also like