import java.util.function.*; import java.util.*; class Truc{ public int a; public Truc(int xx){a=xx;} public Truc(String s){a=10;} public String toString(){ return ""+a; } public static int compareStatic(Integer i1, Integer i2){ return 1; } public int compare(Integer i1, Integer i2){ return -1; } } //////////////////////////////////////////////// /// stream //////////////////////////////////////////////// class TestStream{ public static void main(String[] args){ /////////// // filter /////////// List numbers = Arrays.asList(1, 2, 3, 4, 5); List evens = numbers.stream().filter(n -> n % 2 == 0).toList(); System.out.println(evens); //on enchaîne un filter et un foreach List numbers2 = Arrays.asList(1, 2, 3, 4, 5); numbers2.stream().filter(n -> n % 2 == 1).forEach(n -> System.out.println(n)); /////////// // map /////////// List names = List.of("Alice", "Bob", "Charlie", "Dave"); List upperCaseNames = names.stream() .map(s -> s.toUpperCase()) .toList(); ///////////////////////////////// // méthodes references ///////////////////////////////// //ClassName::staticMethod //objectReference::instanceMethod //ClassName::instanceMethod //ClassName::new List upperCaseNamesV2 = names.stream() .map(String::toUpperCase) //ClassName::staticMethod .toList(); List listeTruc = names.stream() .map(Truc::new) //ClassName::new (appel au constructeur) .toList(); System.out.println(listeTruc); Truc tr = new Truc(5); TreeSet ts = new TreeSet<>(Truc::compareStatic); //ClassName::staticMethod TreeSet ts2 = new TreeSet<>(tr::compare); //objectReference:instanceMethod List l = new ArrayList<>(); l.add("bonjour"); l.add(null); l.add("bonjour2"); //les 3 lignes sont équivalentes List lNonNull = l.stream().filter(s -> s != null).toList(); lNonNull = l.stream().filter(Objects::nonNull).toList(); lNonNull = l.stream().filter(MethodesStatiques::m).toList(); System.out.println(lNonNull); //rmq : limite des method reference, certaines interfaces fonctionelles ne sont pas exprimables TreeSet t = new TreeSet<>((a,b) -> {int x = Truc.compareStatic(a,b); if(a>b) return x+2; else return x-2;}); //TreeSet t = new TreeSet<>(Truc::compareStatic et .. exprimer +2 ou -2 ?? impossible en method reference ); } } class MethodesStatiques{ public static boolean m(String s){ return s!=null; } } ///////////////// // autre exemple où l'on crée une méthode (createTruc) qui prend en param une interface fonctionelle (et donc un cas où utilise une interf fonctionelle PAS dans une lambda) //////////////// class Example { public static void main(String[] args) { // Using a lambda expression Truc t1 = createTruc(value -> new Truc(value)); // Using a method reference Truc t2 = createTruc(Truc::new); System.out.println(t1); System.out.println(t2); } public static Truc createTruc(MyFactory factory) { return factory.create(5); } } @FunctionalInterface interface MyFactory { Truc create(int value); }