Προγραμματισμός ΙΙ: Εκφράσεις Lambda

Προγραμματισμός ΙΙ

Εκφράσεις Lamda

Εκφράσεις Lambda

Παράδειγμα (1)

    (Short a) -> return (short)(a / 35);
    (a) -> return a * a / a + a - a;
    (param) -> {
        System.out.println("param: " + param);
        return "return value";
    }

Μέθοδος accept

import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
    c.accept("Java2s.com");
  }
}

Μέθοδος apply

import java.util.function.Function;

public class Decess {
    public static Function<Integer,
        Integer> multiplyThreeElements(int b, int c) {
        return (a) -> a * b * c;
    }

    public static void main(String[] args) {
         System.out.println(multiplyThreeElements(3,3).apply(2));
 }
}

Παράδειγμα (2)

import java.util.function.Function;

public class Lambda {
        public static Function<Long, Long> divideThem(Function<Long,
                Long> divideWith) {
                return (Long a) -> (long)(divideWith.apply(a / 15));
        }

        public static void main(String[] args) {

                Function<Long, Long> divideWith =
                    (Long a) -> (long) (100 / a);
                System.out.println(divideThem(divideWith)
                    .apply(new Long(30)));
        }
}

Μέθοδος compose

import java.util.function.Function;

public class Main {

  public static void main(String[] args) {
    Function<Integer,String> converter = (i)-> Integer.toString(i);
    
    Function<String, Integer> reverse = (s)-> Integer.parseInt(s);
   
    System.out.println(converter.apply(3).length());
    System.out.println(converter.compose(reverse).apply("30").length());
  }
}

Παράδειγμα (3)

import java.util.function.Function;

public class Decess {

    public static Function<Integer,
    Integer> multiplyThreeElements(int b, int c) {
        return (a) -> a * b * c;
    }

    public static void main(String[] args) {
        Function<Integer, Integer> multiplyAgain =
                multiplyThreeElements(3, 3)
                .compose(multiplyThreeElements(2, 2));
        System.out.println(multiplyAgain.apply(2));
    }
}

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.