Vous êtes sur la page 1sur 64

PROGRAMMATION EN JAVA

Semaine 4:
Les collections
Lecturer: NGUYỄN Thị Minh Tuyền
Plan du cours 2

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Plan du cours 3

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
java.util – Classes de haut niveau [1] 4

Programmation en Java
java.util – Classes de haut niveau [1] 5

Programmation en Java
java.util – Interfaces 6

Programmation en Java
Aperçu des collections [1] 7

• Le cadre des collections Java standardise la manière dont


les groupes d'objets sont gérés par vos programmes.
• Le cadre des collections a été conçu pour répondre à
plusieurs objectifs.
• Haute performance.
• Permettre à différents types de collections de fonctionner de la
même manière et avec un degré élevé d'interopérabilité.
• Facile à étendre et / ou adapter une collection.
• Autoriser l'intégration de tableaux standard dans le cadre des
collections Java.
• Les algorithmes font partie du mécanisme de collection.
• Fournir l'interface Iterator.

Programmation en Java
Aperçu des collections [2] 8

• JDK 8 a ajouté un autre type d'itérateur appelé spliterator.


• Le cadre définit également plusieurs interfaces et classes
de map.
• Les maps stockent des paires clé / valeur.

Programmation en Java
Interface Iterable
extends

Class
9
implements
Collection AbstractCollection

AbstractSet

HashSet
List Queue Set

AbstractList AbstractQueue EnumSet

AbstractSe PriorityQueue LinkedHashSets


quentialList

SortedSet
LinkedList Deque

NavigableSet
ArrayList ArrayDeque
TreeSet
Plan du cours 10

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Interfaces de Collection 11

Programmation en Java
Interface Iterable extends
12
Class
implements
Collection

List Queue Set

Deque

SortedSet

NavigableSet
Programmation en Java
Plan du cours 13

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Classes de Collection 14

Programmation en Java
Interface Iterable
extends

15
Class Collection AbstractCollection
implements

AbstractSet

HashSet
List Queue Set

AbstractList AbstractQueue EnumSet

AbstractSe PriorityQueue LinkedHashSets


quentialList

SortedSet
LinkedList Deque

NavigableSet
ArrayList ArrayDeque
Programmation en Java TreeSet
Classe ArrayList 16

• Étend AbstractList et implémente l'interface List.


class ArrayList<E>
• E spécifie le type d'objets que la liste contiendra.
• Prend en charge les tableaux dynamiques qui peuvent
évoluer au besoin.
• Est un tableau de longueur variable de références
d'objets
• Les listes de tableaux sont créées avec une taille initiale.
• Lorsque cette taille est dépassée, la collection est
automatiquement agrandie.

Programmation en Java
Constructeurs 17

• Constructeurs:
ArrayList()
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)

Programmation en Java
1. import java.util.*;
2. class ArrayListDemo { 18
3. public static void main(String args[]) {
4. ArrayList<String> al = new ArrayList<String>();
5. System.out.println("Initial size of al: " + al.size());
6. al.add("C"); al.add("A"); al.add("E"); al.add("B");
7. al.add("D"); al.add("F"); al.add(1, "A2");
8. System.out.println("Size of al after additions: " +
9. al.size());
10. System.out.println("Contents of al: " + al);
11.

12. al.remove("F"); al.remove(2);


13. System.out.println("Size of al after deletions: " +
14. al.size());
15. System.out.println("Contents of al: " + al);
16. }
17. } Programmation en Java
Obtention d'un tableau à partir
d'un ArrayList 19

object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
default <T> T[] toArray(IntFunction<T[]>
arrayGen)

Programmation en Java
1. //Convert an ArrayList into an array.
2. public class ArrayListToArray { 20
3. public static void main(String args[]) {
4. // Create an array list.
5. ArrayList<Integer> al = new ArrayList<Integer>();
6. // Add elements to the array list.
7. al.add(1); al.add(2); al.add(3); al.add(4);
8. System.out.println("Contents of al: " + al);
9. // Get the array.
10. Integer ia[] = new Integer[al.size()];
11. ia = al.toArray(ia);
12. int sum = 0;
13. // Sum the array.
14. for (int i : ia) sum += i;
15. System.out.println("Sum is: " + sum);
16. }
17. }
Programmation en Java
Plan du cours 21

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Accéder à une collection via un
Iterator 22

• Pour parcourir les éléments d'une collection: utilisez un


itérateur, qui est un objet qui implémente l'interface
Iterator ou ListIterator.
• Iterator vous permet de parcourir une collection, d'obtenir ou
de supprimer des éléments.
• ListIterator étend Iterator pour permettre le parcours
bidirectionnel d'une liste et la modification d'éléments.
interface Iterator<E>
interface ListIterator<E>
• E spécifie le type d'objets en cours d'itération.

Programmation en Java
Méthodes d'Iterator 23

Methods Description

default void Performs the given action for each


remaining element until all elements have
forEachRemaining(Consumer<?
been processed or the action throws an
super E> action)
exception.

boolean hasNext() Returns true if the iteration has more


elements.
E next() Returns the next element in the iteration.
Removes from the underlying collection the
default void remove() last element returned by this iterator
(optional operation).

Programmation en Java
Méthodes de ListIterator 24
Methods Description
void add(E e) Inserts the specified element into the list.
Returns true if this list iterator has more elements
boolean hasNext() when traversing the list in the forward direction.
Returns true if this list iterator has more elements
boolean hasPrevious() when traversing the list in the reverse direction.
Returns the next element in the list and advances the
E next() cursor position.
Returns the index of the element that would be
int nextIndex() returned by a subsequent call to next().
Returns the previous element in the list and moves the
E previous() cursor position backwards.
Returns the index of the element that would be
int previousIndex() returned by a subsequent call to previous().
Removes from the list the last element that was
void remove() returned by next() or previous() (optional operation).
Replaces the last element returned
void set(E e)
Programmation en Java
by next() or previous() with the specified element.
Utiliser un Iterator 25

1. Obtenir un itérateur au début de la collection en


appelant la méthode iterator() de la collection.
2. Configurer une boucle qui appelle hasNext(). Itérer la
boucle tant que hasNext() renvoie true.
3. Dans la boucle, obtenir chaque élément en appelant
next().

Programmation en Java
26
1. class IteratorDemo {
2. public static void main(String args[]) {
3. ArrayList<String> al = new ArrayList<String>();
4. al.add("C"); al.add("A"); al.add("E"); al.add("B");
5. al.add("D"); al.add("F");
6. System.out.print("Original contents of al: ");
7. Iterator<String> itr = al.iterator();
8. while (itr.hasNext()) {
9. String element = itr.next();
10. System.out.print(element + " ");
11. }
12. System.out.println();

Programmation en Java
1. ListIterator<String> litr = al.listIterator();
2. while (litr.hasNext()) { 27
3. String element = litr.next();
4. litr.set(element + "+");
5. }
6. System.out.print("Modified contents of al: ");
7. itr = al.iterator();
8. while (itr.hasNext()) {
9. String element = itr.next();
10. System.out.print(element + " ");
11. } System.out.println();
12. System.out.print("Modified list backwards: ");
13. while (litr.hasPrevious()) {
14. String element = litr.previous();
15. System.out.print(element + " ");
16. } System.out.println();
17. }
Programmation en Java
18. }
Utiliser For-Each 28
1. class ForEachDemo {
2. public static void main(String args[]) {
3. ArrayList<Integer> vals = new ArrayList<Integer>();
4. vals.add(1); vals.add(2); vals.add(3);
5. vals.add(4); vals.add(5);
6. System.out.print("Original contents of vals: ");
7. for (int v : vals) System.out.print(v + " ");
8. System.out.println();
9. // Now, sum the values by using a for loop.
10. int sum = 0;
11. for (int v : vals) sum += v;
12. System.out.println("Sum of values: " + sum);
}
13. } Programmation en Java
Plan du cours 29

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Travailler avec Maps 30

• Une carte (Map) est un objet qui stocke des associations


entre des clés et des valeurs, ou des paires clé / valeur.
• Étant donné une clé, vous pouvez trouver sa valeur.
• Les clés et les valeurs sont des objets.
• Les clés doivent être uniques, mais les valeurs peuvent être
dupliquées.
• Certaines Maps peuvent accepter une clé nulle et des valeurs
nulles, d'autres non.
• Maps n'implémente pas l'interface Iterable.
• Vous ne pouvez pas parcourir une carte en utilisant une boucle
for de style for-each.
• Vous ne pouvez pas obtenir d’itérateur sur un Map.

Programmation en Java
Interfaces de Map 31

Interface Description
Map Maps unique keys to values
Describes an element (key-value pair) in a map. This is an
Map.Entry
inner class of Map.
Extends SortedMap to handle the retrieval of entries
NavigableMap
based on closest-match searches
Extends Map so that the keys are maintained in ascending
SortedMap
order

Programmation en Java
Interface
extends
32
Class
implements

Map.Entry
AbstractMap Map
(Inner class of Map)

EnumMap

HashMap
SortedMap

TreeMap

WeakHashMap

LinkedHashMap NavigableMap
Programmation en Java

IdentityHashMap
Classes de Map 33

Programmation en Java
Classe HashMap 34

• Étend AbstractMap et implémente l'interface Map.


• Il utilise une table de hachage pour stocker le Map.
• Cela permet au temps d'exécution de get() et put() de rester
constant même pour les grands ensembles.
class HashMap<K, V>
• K spécifie le type de clés et V spécifie le type de valeurs.
• Constructeurs:
• HashMap()
• HashMap(Map<? extends K, ? extends V> m)
• HashMap(int capacity)
• HashMap(int capacity, float fillRatio)

Programmation en Java
Exemple [1] 35

1. import java.util.*;
2. class HashMapDemo {
3. public static void main(String args[]) {
4. HashMap<String, Double> hm = new HashMap<String,
5.
Double>();

6.
hm.put("John Doe", new Double(3434.34));

7.
hm.put("Tom Smith", new Double(123.22));

8.
hm.put("Jane Baker", new Double(1378.00));

9.
hm.put("Tod Hall", new Double(99.22));

10.
hm.put("Ralph Smith", new Double(-19.08));

11.

12.

Programmation en Java
Exemple [2] 36

1. Set<Map.Entry<String, Double>> set = hm.entrySet();


2. for (Map.Entry<String, Double> me : set) {
3. System.out.print(me.getKey() + ": ");
4. System.out.println(me.getValue());
5. }
6. System.out.println();
7. double balance = hm.get("John Doe");
8. hm.put("John Doe", balance + 1000);
9. System.out.println("John Doe's new balance: " +
10. hm.get("John Doe"));
11. }
12. }

Programmation en Java
Plan du cours 37

1. Aperçu des collections


2. Interfaces de collection
3. Classes de collection
4. Accéder à une collection via un itérateur
5. Travailler avec map
6. Comparateurs

Programmation en Java
Comparators [1] 38

• TreeSet et TreeMap stockent les éléments dans un ordre


trié.
• C'est le comparateur qui définit précisément ce que signifie
«ordre trié».
• Par défaut, ces classes stockent leurs éléments en utilisant ce que
Java appelle un «ordre naturel»
• Pour classer les éléments d'une manière différente:
spécifiez ensuite un comparateur lorsque vous construisez
l'ensemble ou la carte à régissez précisément la manière
dont les éléments sont stockés dans des collections et des
cartes triées.
interface Comparator<T>
• T spécifie le type d'objets comparés.
Programmation en Java
Comparators [2] 39

• Avant JDK 8: l'interface de Comparator ne définissait que


deux méthodes:
int compare(T obj1, T obj2)
• obj1 et obj2 sont les objets à comparer.
boolean equals(object obj)
• obj est l'objet à tester pour l'égalité.
• JDK 8 a ajouté une nouvelle fonctionnalité significative à
Comparator grâce à l'utilisation de méthodes d'interface
par défaut et statiques.

Programmation en Java
40

Methods Description
int compare(T o1, T o2) Compares its two arguments for order.
Indicates whether some other object is
boolean equals(Object obj)
"equal to" this comparator.
static <T extends Comparable<? Returns a comparator that
super T>>Comparator<T> compares Comparable objects in natural
naturalOrder() order.
static <T> Comparator<T>
Returns a null-friendly comparator that
nullsFirst (Comparator<? super
considers null to be less than non-null.
T> comparator)
static <T> Comparator<T>
Returns a null-friendly comparator that
nullsLast (Comparator<? super
considers null to be greater than non-null.
T> comparator)
Returns a comparator that imposes the
default Comparator<T> reversed()
reverse ordering of this comparator.
static <T extends Comparable<? Returns a comparator that imposes the
super T>>Comparator<T> reverse of the natural ordering.
reverseOrder()
Programmation en Java
41

Methods Description
static <T,U extends Comparable<?
Accepts a function that extracts a Comparable sort
super U>>Comparator<T>
key from a type T, and returns
comparing(Function<? super T,?
a Comparator<T> that compares by that sort key.
extends U> keyExtractor)
static <T,U> Comparator<T>
Accepts a function that extracts a sort key from a
comparing(Function<? super T,?
type T, and returns a Comparator<T> that
extends
compares by that sort key using the
U> keyExtractor, Comparator<?
specified Comparator.
super U> keyComparator)
static <T> Comparator<T> Accepts a function that extracts a double sort key
comparingDouble(ToDoubleFunction<? from a type T, and returns a Comparator<T> that
super T> keyExtractor) compares by that sort key.
static <T> Comparator<T> Accepts a function that extracts an int sort key from
comparingInt(ToIntFunction<? super a type T, and returns a Comparator<T> that
T> keyExtractor) compares by that sort key.
static <T> Comparator<T> Accepts a function that extracts a long sort key from
comparingLong(ToLongFunction<? a type T, and returns a Comparator<T> that
super T> keyExtractor) compares by that sort key.
42
Methods Description
default Comparator<T>
Returns a lexicographic-order comparator with
thenComparing(Comparator<?
another comparator.
super T> other)
default <U extends Comparable<?
super U>>Comparator<T>thenComparing Returns a lexicographic-order comparator with
(Function<? super T,? extends a function that extracts a Comparable sort key.
U> keyExtractor)
default <U> Comparator<T>
thenComparing(Function<? super T,? Returns a lexicographic-order comparator with a
extends function that extracts a key to be compared with
U> keyExtractor, Comparator<? super the given Comparator.
U> keyComparator)
default Comparator<T>
Returns a lexicographic-order comparator with a
thenComparingDouble(ToDoubleFunctio
function that extracts a double sort key.
n<? super T> keyExtractor)
default Comparator<T>
Returns a lexicographic-order comparator with a
thenComparingInt(ToIntFunction<?
function that extracts an int sort key.
super T> keyExtractor)
default Comparator<T>
Returns a lexicographic-order comparator with a
thenComparingLong(ToLongFunction<?
function that extracts a long sort key.
super T> keyExtractor)
Exemple: Utiliser un Comparator [1] 43

1. //Use a custom comparator.


2. import java.util.*;
3. //A reverse comparator for strings.
4. class MyComp implements Comparator<String> {
5. public int compare(String aStr, String bStr) {
6. // Reverse the comparison.
7. return bStr.compareTo(aStr);
8. }
9. // No need to override equals or the default methods.
10. }

Programmation en Java
Exemple: Utiliser un Comparator [2] 44

1. import java.util.TreeSet;
2. class CompDemo {
3. public static void main(String args[]) {
4. TreeSet<String> ts = new
5. TreeSet<String>(new MyComp());
6. ts.add("C"); ts.add("A"); ts.add("B");
7. ts.add("E"); ts.add("F"); ts.add("D");
8. // Display the elements.
9. for (String element : ts)
10. System.out.print(element + " ");
11. System.out.println();
12. }
13. }
Programmation en Java
45

1. import java.util.*;
2. class CompDemo2 {
3. public static void main(String args[]) {
4. TreeSet<String> ts = new TreeSet<String>((aStr, bStr)
5. -> bStr.compareTo(aStr));
6. // Add elements to the tree set.
7. ts.add("C"); ts.add("A"); ts.add("B");
8. ts.add("E"); ts.add("F"); ts.add("D");
9. // Display the elements.
10. for (String element : ts)
11. System.out.print(element + " ");
12. System.out.println();
13. }
Programmation en Java
14. }
46

1. import java.util.*;
2. class TComp implements Comparator<String> {
3. public int compare(String aStr, String bStr) {
4. int i, j, k;
5. // Find index of beginning of last name.
6. i = aStr.lastIndexOf(' '); j = bStr.lastIndexOf(' ');
7. k = aStr.substring(i)
8. .compareToIgnoreCase(bStr.substring(j));
9. if (k == 0) // last names match, check entire name
10. return aStr.compareToIgnoreCase(bStr);
11. else return k;
12. }
13. }
Programmation en Java
47

1. class TreeMapDemo2 {
2. public static void main(String args[]) {
3. // Create a tree map.
4. TreeMap<String, Double> tm = new TreeMap<String,
5.
Double>(new TComp());

6.
// Put elements to the map.

7.
tm.put("John Doe", new Double(3434.34));

8.
tm.put("Tom Smith", new Double(123.22));

9.
tm.put("Jane Baker", new Double(1378.00));

10.
tm.put("Tod Hall", new Double(99.22));

11.
tm.put("Ralph Smith", new Double(-19.08));

12.
// Get a set of the entries.

13.
Set<Map.Entry<String, Double>> set = tm.entrySet();
Programmation en Java
48

1. // Display the elements.


2. for (Map.Entry<String, Double> me : set) {
3. System.out.print(me.getKey() + ": ");
4. System.out.println(me.getValue());
5. }
6. System.out.println();
7. // Deposit 1000 into John Doe's account.
8. double balance = tm.get("John Doe");
9. tm.put("John Doe", balance + 1000);
10.

11. System.out.println("John Doe's new balance: " +


12. tm.get("John Doe"));
13. }
Programmation en Java
14. }
49

1. import java.util.*;
2. //A comparator that compares last names.
3. class CompLastNames implements Comparator<String> {
4. public int compare(String aStr, String bStr) {
5. int i, j;
6. // Find index of beginning of last name.
7. i = aStr.lastIndexOf(' ');
8. j = bStr.lastIndexOf(' ');
9. return aStr.substring(i)
10. .compareToIgnoreCase(bStr.substring(j));
11. }
12. }
13.
Programmation en Java
50

1. import java.util.Comparator;
2. //Sort by entire name when last names are equal.
3. class CompThenByFirstName implements Comparator<String> {
4. public int compare(String aStr, String bStr) {
5. return aStr.compareToIgnoreCase(bStr);
6. }
7. }
8.

9.

Programmation en Java
51

1. class TreeMapDemo2A {
2. public static void main(String args[]) {
3. CompLastNames compLN = new CompLastNames();
4. Comparator<String> compLastThenFirst =
5.
compLN.thenComparing(new CompThenByFirstName());

6.
TreeMap<String, Double> tm = new TreeMap<String,

7.
Double>(compLastThenFirst);

8.
tm.put("John Doe", new Double(3434.34));

9.
tm.put("Tom Smith", new Double(123.22));

10.
tm.put("Jane Baker", new Double(1378.00));

11.
tm.put("Tod Hall", new Double(99.22));

12.
tm.put("Ralph Smith", new Double(-19.08));

13.
Set<Map.Entry<String, Double>> set = tm.entrySet();
Programmation en Java
52

1. for (Map.Entry<String, Double> me : set) {


2. System.out.print(me.getKey() + ": ");
3. System.out.println(me.getValue());
4. }
5. System.out.println();
6.

7. double balance = tm.get("John Doe");


8. tm.put("John Doe", balance + 1000);
9. System.out.println("John Doe's new balance: " +
10. tm.get("John Doe"));
11. }
12. }

Programmation en Java
Algorithmes de Collection 53

• Le cadre des collections définit plusieurs algorithmes qui


peuvent être appliqués aux collections et aux maps.

Programmation en Java
Algorithmes de Collection 54

Programmation en Java
55

Programmation en Java
56

Programmation en Java
57

Programmation en Java
58

Programmation en Java
59

1. import java.util.*;
2. class AlgorithmsDemo {
3. public static void main(String args[]) {
4. LinkedList<Integer> ll = new LinkedList<Integer>();
5. ll.add(-8); ll.add(20); ll.add(-20); ll.add(8);
6. // Create a reverse order comparator.
7. Comparator<Integer> r = Collections.reverseOrder();
8. // Sort list by using the comparator.
9. Collections.sort(ll, r);
10. System.out.print("List sorted in reverse: ");
11. for (int i : ll) System.out.print(i + " ");
12. System.out.println();

Programmation en Java
60

1. // Shuffle list.
2. Collections.shuffle(ll);
3. // Display randomized list.
4. System.out.print("List shuffled: ");
5. for (int i : ll) System.out.print(i + " ");
6. System.out.println();
7. System.out.println("Minimum: " +
8. Collections.min(ll));
9. System.out.println("Maximum: " +
10. Collections.max(ll));
11. }
12. }

Programmation en Java
Tableaux 61

• La classe Arrays fournit diverses méthodes utiles lors


de l'utilisation de tableaux.
• Ces méthodes aident à combler le fossé entre les
collections et les tableaux.
• Les méthodes implémentées par Arrays peuvent être
trouvées ici:
https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html

Programmation en Java
Exemple 62
1. import java.util.*;
2. class ArraysDemo {
3. public static void main(String args[]) {
4. int array[] = new int[10];
5. for (int i = 0; i < 10; i++) array[i] = -3 * i;
6. System.out.print("Original contents: ");
7. display(array);
8. Arrays.sort(array);
9. System.out.print("Sorted: ");
10. display(array);
11. // Fill and display the array.
12. Arrays.fill(array, 2, 6, -1);
13. System.out.print("After fill(): ");
14. display(array); Programmation en Java
Exemple 63

1. Arrays.sort(array);
2. System.out.print("After sorting again: ");
3. display(array);
4. System.out.print("The value -9 is at location ");
5. int index = Arrays.binarySearch(array, -9);
6. System.out.println(index);
7. }
8. static void display(int array[]) {
9. for (int i : array)
10. System.out.print(i + " ");
11. System.out.println();
12. }
13. }
Programmation en Java
64

QUESTION ?

Programmation en Java

Vous aimerez peut-être aussi