0% found this document useful (0 votes)
7 views

Formation JAVA8

Uploaded by

jlassi.sarraa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Formation JAVA8

Uploaded by

jlassi.sarraa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

05/09/2023

JAVA8
Programmation fonctionnelle

Key words :

Expressions lambda JSR 335

Stream API

Paradigm déclaratif : exemple SQL, xml

Paradigm procédural : PLSQL

Paradigm Interpreté ( notion de State + sauvegarder une variable ) :

Python, architecture : Graphe d’appel(main)

Paradigm fonctionnel : (notion de fonction pure/impure), architecture Pipeline( lazy evaluation )

Paradigm OOP : traitement automatique de l’information : architecture : diagramme de classes

Upcast , downcast

@override : redéfinir

**ComparingtInt**

**********************************************************************************

Abstraction :

> Améliore la réutisabilité, maintenabilité


> On doit override les méthodes dans les classes qui implémentent l’interface

SOLID :
Single-Responsibility Principle · Open for extension -Closed for modification ,interface ,
dependency inversion
Principle Description

Single Responsibility Principle Each class should be responsible for a single part or functionality of

Software components should be open for


Open-Closed Principle
extension, but not for modification.

Objects of a superclass should be replaceable with objects


Liskov Substitution Principle
of its subclasses without breaking the system.

Interface Segregation Principle No client should be forced to depend on methods that it does not us

High-level modules should not depend on low-level


Dependency Inversion Principle
modules, both should depend on abstractions.

- Généralisation ( b hérite les caractéristiques de a , donc b est un a)


- Part of ( b is part of a : instanciation de a dans b)

Interface :

classe purement abstraite(non instanciée) + comportement de la classe qui les implémentent


 Il faut mettre les méthodes (pas toutes les méthodes ) (exemple : afficher() ) dans la classe
mère abstraite + @override + class object implements Deplacement
 Pour les méthodes de « behavior » on crée une interface (exemple : déplacer() dans
l’interface Déplacement

Pour appeler les méthodes de l’interface dans l main : il faut convertir l o

Test :

If (o instanceof Deplacement )

((Deplacement).o).déplacer() ;

Expression lambda :
 one single line : programmation fonctionnelle
 anonymous function
 only 1 single abstract method

Fonction pure : les instructions liés aux paramètres ; no variables

Exemple syntaxe dans Main : Calcul est une interface

Calcul c = new Calcul () {

@override

Int op ( int a , int b ) {

return a+b ;}

};

--- Calcul c = (a,b) -> a+b ; : redéfinitin op

Appel : c.op(3 , 5)
On peut redéfinir op une autre fois :

Calcul c = (a,b) -> a/b ;

c.op(20,4)

 X classe , somme fonction : expression lambda avec une fonction existante :

Calcul c = X :: somme
-----------------------------------------------------------------

Exercice sort (java7) :

Collections.sort(words, new Comparator<Object> () ){

@override

Public int compare(Object o1, Object o2){

Return null ; }

 Java 8 : avec import static :

Collections.sort(words, (s1,s2) -> Integer.compare(s1.length() , s2.length() ) ) ;

 Java 8 avec les references de méthodes et les interfaces fonctionnelles :

Collections.sort(comparator.comparingInt(

----------------------------------------------------------------------------------------------------------------------------

sequentiel : arraylist ,

thread : vector
Collection.sort()

Map : tableau

Set : les variables sont uniques , list : variables non uniques

LinkedHashSet : ordered list

Treeset : insertion par tri,

ArrayList : insertion en fin

 ArrayList:
 Implements a dynamic array to store elements.
 Provides fast random access (constant-time) for reading
elements by index.
 Slower at inserting and deleting elements in the middle
because it may require shifting elements.
 Better suited for scenarios where you need frequent random access
and iteration but fewer insertions and deletions.
 Good for read-heavy use cases.

 LinkedList:
 Implements a doubly-linked list to store elements.
 Provides fast insertion and deletion of elements in the middle
(constant-time) because it only requires changing references.
 Slower at random access (linear-time) because you need to
traverse the list from the beginning or end to access an
element by index.
 Better suited for scenarios where you need frequent insertions and
deletions in the middle of the list.
 Good for write-heavy use cases.

Vector:
 A Vector is a specific data structure provided by some programming
languages like Java (e.g., java.util.Vector).
 It is a part of the Java Collections Framework (prior to Java 1.2) and
is essentially a dynamic array.
 It is synchronized by default, making it thread-safe, but this can
impact performance in multi-threaded scenarios.
They are suitable when you need a resizable array-like data structure, especially
in older Java code where synchronization is required.

List:
1. Data Structure:
 A "list" typically refers to a specific data structure that holds
an ordered collection of elements.
 Lists are commonly used in many programming languages,
and they allow you to store and manipulate data in a
sequence.
2. Usage:
 Lists are used to store and manage a collection of items where
the order of items matters, and you may need to access them
by their index.
 Lists are often used for tasks like maintaining a collection of
items in a specific order, implementing dynamic arrays, and
performing various list-specific operations like adding,
removing, and retrieving elements.
3. Common Examples:
 In Python, you have lists represented by square brackets (e.g.,
[1, 2, 3] ).
 In Java, lists are part of the Java Collections Framework and
can be implemented using classes like ArrayList or LinkedList
(e.g., ArrayList<Integer>

Collections :
"List" and "Collections" are related concepts in programming, but
they have different meanings and usages. Here are the key
differences between them:

List:

1. Data Structure:
 A "list" typically refers to a specific data structure that
holds an ordered collection of elements.
 Lists are commonly used in many programming
languages, and they allow you to store and manipulate
data in a sequence.
2. Usage:
 Lists are used to store and manage a collection of items
where the order of items matters, and you may need to
access them by their index.
 Lists are often used for tasks like maintaining a
collection of items in a specific order, implementing
dynamic arrays, and performing various list-specific
operations like adding, removing, and retrieving
elements.
3. Common Examples:
 In Python, you have lists represented by square
brackets (e.g., [1, 2, 3]).
 In Java, lists are part of the Java Collections Framework
and can be implemented using classes like ArrayList or
LinkedList (e.g., ArrayList<Integer> ).

Collections:

1. Scope:
 "Collections" is a broader term that refers to a group of
elements or objects.
 It is a more general concept than a "list" and can
encompass various data structures like lists, sets,
maps, and more.
2. Usage:
 Collections are used to manage and manipulate groups
of data or elements. They don't necessarily imply a
specific order or indexing mechanism.
 The term "collections" is often associated with libraries
or frameworks that provide data structures and
algorithms for handling collections of data in a more
abstract and generalized way.
3. Common Examples:
 In Java, the term "collections" often refers to the Java
Collections Framework, which includes interfaces like
List, Set, Map, and various implementations for each. It
provides a comprehensive set of data structures for
managing collections.
 In Python, collections can refer to various built-in data
types like lists, sets, and dictionaries, but it can also
refer to the collections module, which provides
specialized data structures like namedtuple, deque, and
Counter.

In summary, a "list" is a specific data structure for managing an


ordered collection of elements, while "collections" is a more
general term that encompasses a wide range of data structures
used for managing collections of data. When discussing collections
in programming, it's important to clarify whether you are referring
to a specific list or a broader concept of collections that includes
various data structures.
1. Interfaces :
List (e.g., ArrayList, LinkedList, Vector):
 add(E element) : Add an element to the end of the list.
 add(int index, E element) : Insert an element at a specific
position.
 remove(int index) : Remove and return an element by index.
 remove(Object o) : Remove the first occurrence of an element.
 get(int index) : Get the element at a specific index.
 set(int index, E element) : Set the element at a specific index.
 indexOf(Object o) : Find the index of the first occurrence of an
element.
 size(): Get the number of elements in the list.

2. Set (e.g., HashSet, LinkedHashSet, TreeSet):


 add(E element) : Add an element to the set.
 remove(Object o) : Remove an element from the set.
 contains(Object o) : Check if an element exists in the set.
 size(): Get the number of elements in the set.
3. Map (e.g., HashMap, LinkedHashMap, TreeMap):
4. put(K key, V value): Add a key-value pair to the map.
5. get(Object key): Get the value associated with a key.
6. remove(Object key): Remove a key-value pair by key.
7. containsKey(Object key): Check if a key exists in the map.
8. keySet(): Get a set of keys.
9. values(): Get a collection of values.
10. entrySet(): Get a set of key-value pairs (entries).

Classes (from java.util package):

1. Collections (Utility class):


 sort(List<T> list) : Sort a list in natural order.
 reverse(List<?> list) : Reverse the order of elements in a list.
 shuffle(List<?> list) : Shuffle the elements in a list.
 binarySearch(List<? extends Comparable<? super T>> list, T
key): Perform a binary search on a sorted list.
 max(Collection<? extends T> coll) : Find the maximum element
in a collection.
 min(Collection<? extends T> coll) : Find the minimum element
in a collection.
2. Arrays (Utility class):
 asList(T... a) : Convert an array to a List.
 sort(T[] a): Sort an array in natural order.
 binarySearch(T[] a, T key) : Perform a binary search on a sorted
array.
 toString(T[] a) : Convert an array to a string representation.
MAP :

The Map interface defines a set of methods for working with key-value
pairs. Some of the commonly used methods include:

1. put(K key, V value): Associates the specified value with the specified
key in the map.
2. get(Object key): Returns the value to which the specified key is
mapped, or null if the key is not found.
3. remove(Object key): Removes the key-value pair with the specified
key from the map and returns the value.
4. containsKey(Object key): Checks if the map contains a mapping for
the specified key.
5. keySet(): Returns a set of all keys in the map.
6. values(): Returns a collection of all values in the map.
7. entrySet(): Returns a set of key-value pairs (entries) in the map.

-----------------------------------------------------------------------------------

Dans la classe anonyme : Utilisation d’une variable globale ne peut pas être modifiable -> must be
final

Default functions : on peut la redéfinir dans les classes filles

Static functions : méthode de classe, méthode testa3mel que les paramètres mte3ha, on peut
l’appeler sans faire l’instanciation de la classe

Public static vois traite (int n , Calculator cal ) { ..}

Interface fonctionnelle :

 Une seule méthode abstraite


 @FunctionalInterface
Optional: The Optional class is introduced to handle the absence of a
value (null) more gracefully. It encourages developers to explicitly handle
the case where a value might be absent, reducing null pointer exceptions.

You might also like