Java8 глубокого понимания Lambda

лямбда-выражения боя

Примеры взяты из лямбды

Создать попутную Runnable тему

  • Перед java8
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() { // do something } }); 
  • После того, как Java 8
new Thread(()->{});

Приведенный выше пример является относительно простым, но есть два вопроса. Что такое лямбда-выражение? Как использовать лямбда-выражения?

Что такое лямбда-выражение?

Исходя из приведенного выше примера, сначала мы знаем Lambda обычно представляет собой анонимный объект, во-вторых кличут «->», IDE поможет нам войти в функции интерфейс должны соответствовать спецификациям лямбды. Мы наблюдаем это изменение в классе-совместимый.

  • java7 Runnable
// 省略注释
package java.lang;
public interface Runnable { public abstract void run(); } 
  • java8 Runnable
// 省略注释
package java.lang;
@FunctionalInterface
public interface Runnable { public abstract void run(); } 

Мы нашли java8 добавили комментарий @FunctionalInterface Runnable интерфейс. Ниже мы рассмотрим, что здесь вместе аннотацию Да.

Функциональный интерфейс

/**
 * An informative annotation type used to indicate that an interface
 * type declaration is intended to be a <i>functional interface</i> as
 * defined by the Java Language Specification.
 *
 * Conceptually, a functional interface has exactly one abstract
 * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
 * default methods} have an implementation, they are not abstract.  If
 * an interface declares an abstract method overriding one of the
 * public methods of {@code java.lang.Object}, that also does
 * <em>not</em> count toward the interface's abstract method count
 * since any implementation of the interface will have an
 * implementation from {@code java.lang.Object} or elsewhere.
 *
 * <p>Note that instances of functional interfaces can be created with
 * lambda expressions, method references, or constructor references.
 *
 * <p>If a type is annotated with this annotation type, compilers are
 * required to generate an error message unless:
 *
 * <ul>
 * <li> The type is an interface type and not an annotation type, enum, or class.
 * <li> The annotated type satisfies the requirements of a functional interface.
 * </ul>
 *
 * <p>However, the compiler will treat any interface meeting the
 * definition of a functional interface as a functional interface
 * regardless of whether or not a {@code FunctionalInterface}
 * annotation is present on the interface declaration.
 *
 * @jls 4.3.2. The Class Object
 * @jls 9.8 Functional Interfaces
 * @jls 9.4.3 Interface Method Body
 * @since 1.8
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {} 
  • Ядро означает верхнюю часть документа является: @FunctionInterface аннотации, чтобы показать, что этот класс является функцией интерфейса.
  • Интерфейс Функция имеет такую ​​характеристику: только абстрактный метод. java8 предоставляет метод по умолчанию, и метод суперкласса Object (ToString, Равен), эти методы не абстрактный метод расчета количества статистических данных.
  • Использование: функциональный интерфейс с лямбда-выражений, ссылок, метод с использованием эталонной конфигурации.
  • Если вы отметите эту аннотацию на классе, компилятор будет проверяться во время компиляции
  • Наконец, даже если мы не будем отмечать эту аннотацию, компилятор будет рассматривать его как функциональный интерфейс

Ну, мы знаем, с вершины характеристик лямбды, то давайте поговорим о том, как использовать дальше?

Как использовать лямбда

Во-первых, мы Quguan доступа к сети Java8 новых функций, найти описание лямбда-выражений. Мы «Синтаксис лямбда-выражений» ** ** Этот раздел начинается с документа, вероятно, можно получить следующие выводы.

состав Lambda

Лямбда в основном состоит из нескольких частей ниже; списка параметров, разъем тела.

  • Список параметров
    • Внутри скобок, параметры «» разделены. (Строка а, объект б).
    • Кроме того, тип и параметры скобки, могут быть опущены в некоторых случаях
  • Стрелка знак
    • К «->» Эта особая символическая форма, до и после подключения.
  • предмет
    • Он может состоять из одного выражения или блока операторов.
    • Одно выражение, такие как "System.out.println (" XXX ")"
    • Заявление блока
      • Пример 1
      	{
      	System.out.println("xxx");
      	}
      
      • Пример 2
      	{
      	// do something return some result
      	return 100; } 

Лямбда примеры полного использования

Значение лямбды без обратного примера

Цель будет заключаться в достижении конкретной бизнес-сделку с вызывающим абонентом.

  • Определить невозвратное значение, в соответствии со стандартным интерфейсом объектами FunctionInterface
interface Print<String>{
    void printName(String string);
}
Использование Пример 1

Бизнес-логика у меня здесь операция печати на основе входных параметров, журнал выполнения. Актуальный бизнес-сценарии может соответствовать отправить сообщение или операцию конкретной такой MQ.

public class LambdaDemo {
    public static void main(String[] args) { PrintSomeThing(name->System.out.println(name),"Hello baigt"); } public static void PrintSomeThing(Print<String> str,String name) { str.printName(name); } } 
Использование Пример 1 Использование расширенного
  • Используйте определение класса
class Doctor{
    String name;
    String interest;
    public Doctor(String name, String interest) { this.name = name; this.interest = interest; } public void printName(Print<String> str) { str.printName(name); } } 
  • Специальное применение
 Doctor doctor=new Doctor("baigt","java and javascript");
 doctor.printName(name->System.out.println(name));
Она возвращает значение лямбды с помощью примера

Цель будет заключаться в достижении конкретной бизнес-сделку с абонентом, и возвращает результат.

  • Определить возвращаемое значение, в соответствии со стандартным интерфейсом объектов FunctionInterface
interface GetSomething<String>{
    String getThing(); } 
  • Определение пользователя
class Doctor{
    String name;
    String interest;
    public Doctor(String name, String interest) { this.name = name; this.interest = interest; } public String getInterest(GetSomething<String> get) { return get.getThing()+","+name; } } 
  • Примеры использования

бизнес-логика я здесь основана на входных параметрах (неявные проценты), возвращаемый результат вычисляется из, и результатов этой операции печати выполняется.

 Doctor doctor=new Doctor("baigt","java and javascript");
 System.out.println(doctor.getInterest(() -> "Hi")); 

Для того, чтобы здесь, мы, вероятно, понимают основное использование лямбда-выражения. Но будет два вопроса?

  • Лучшие примеры наших пользовательских интерфейсов несколько функций, то есть другие часто используемые функции интерфейса?
  • Функция интерфейса не только за счет использования лямбда-выражений, ссылка может быть также использована и сконфигурирована с помощью стандартного метода. Так эта ссылка, как это было?

Общий интерфейс функции

Мы проверили ноты класса @FunctionInterface, найти функцию Usages по Иде найдет в java.util.function пакет java8 добавил много класса. Вот выбрать несколько базисов (другой основной вариант усиливается или функциональный) есть. Как правило, есть очень мало.

  • потребитель
  • поставщик
  • сказуемое
  • функция

Ниже будет делать простое описание и использование. Вы не можете быть осторожным, чтобы говорить каждый Апи. Он разработан, чтобы позволить вам быстро ознакомиться с java8 лямбда.

потребитель

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8 */ @FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); /** * Returns a composed {@code Consumer} that performs, in sequence, this * operation followed by the {@code after} operation. If performing either * operation throws an exception, it is relayed to the caller of the * composed operation. If performing this operation throws an exception, * the {@code after} operation will not be performed. * * @param after the operation to perform after this operation * @return a composed {@code Consumer} that performs in sequence this * operation followed by the {@code after} operation * @throws NullPointerException if {@code after} is null */ default Consumer<T> andThen(Consumer<? super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } } 

Во-первых, этот интерфейс только абстрактный метод принимает метод получает ссылку в, не возвращают результат.

Используйте определение класса

    public static void doConsumer(Consumer consumer,String input) { consumer.accept(input); } 
  • Использование Пример 1

Прием «что-то вход» вход и выполнить операцию печати

 Consumer consumer = input -> System.out.println(input);
 doConsumer(consumer,"something input");
  • Использование Пример 2

Потребитель два ссылки на операцию, после выполнения andThen.

Consumer consumer = input -> System.out.println(input);
doConsumer(consumer.andThen(input2->{
            System.out.println("input2");
        }),"something input");

поставщик

/**
 * Represents a supplier of results.
 *
 * <p>There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #get()}.
 *
 * @param <T> the type of results supplied by this supplier
 *
 * @since 1.8
 */
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); } 

Во-первых, этот интерфейс только абстрактный метод прибудете, который не принимает никаких аргументов и возвращает результат типа T.

Используйте определение класса

    public static <T> T doSupplier(Supplier<T> supplier) { return supplier.get(); } 
  • Использование Пример 1

Параметр не передается, объект указанного типа, чтобы сгенерировать строку или целое число

 System.out.println(doSupplier(() -> "baigt"));
 System.out.println(doSupplier(() -> {return Integer.valueOf("10");})); 

сказуемое

import java.util.Objects;

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8 */ @FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t); /** * Returns a composed predicate that represents a short-circuiting logical * AND of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code false}, then the {@code other} * predicate is not evaluated. * * <p>Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ANDed with this * predicate * @return a composed predicate that represents the short-circuiting logical * AND of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default Predicate<T> and(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) && other.test(t); } } 

Во-первых, этот интерфейс только абстрактный метод испытания, который принимает объект типа T и возвращает логический результат.

Используйте определение класса

    public static boolean doPredicate(Predicate<String> predicate,String string) { return predicate.test(string); } 
  • Использование Пример 1

В зависимости от условий, он определяет, действительно ли правила фильтрации входного объекта.

System.out.println(doPredicate(input -> input.length() > 5, "12345"));
System.out.println(doPredicate(((Predicate<String>) (input -> input.length() > 5)) .and(input -> input.equalsIgnoreCase("12345")), "12345")); 

функция

import java.util.Objects;

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8 */ @FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t); /** * Returns a composed function that first applies the {@code before} * function to its input, and then applies this function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param <V> the type of input to the {@code before} function, and to the * composed function * @param before the function to apply before this function is applied * @return a composed function that first applies the {@code before} * function and then applies this function * @throws NullPointerException if before is null * * @see #andThen(Function) */ default <V> Function<V, R> compose(Function<? super V, ? extends T> before) { Objects.requireNonNull(before); return (V v) -> apply(before.apply(v)); } /** * Returns a composed function that first applies this function to * its input, and then applies the {@code after} function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param <V> the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after this function is applied * @return a composed function that first applies this function and then * applies the {@code after} function * @throws NullPointerException if after is null * * @see #compose(Function) */ default <www.javachenglei.com> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } /** * Returns a function that always returns its input argument. * * @param <T> the type of the input and output objects to the function * @return a function that always returns its input argument */ static <T> Function<T, T> identity(www.yasenyule.com ) { return t -> t; } } 

Во-первых, только интерфейс Применить абстрактный метод, метод получает объект типа T и возвращает результат типа R.

Используйте определение класса

    public static Integer doFunction(Function<String,Integer> function,String input) { return function.apply(input); } 
  • Использование Пример 1

Получение строки в параметры, возвращают результаты типа Integer. Конкретные примеры не ненормальности определения.

System.out.println(doFunction(input -> input.length(), "baigt"));
// 上述结果为 5
 System.out.println(doFunction(((Function<String, Integer> www.dayuzaixianyl.cn ) (input -> input.length())).compose(input -> String.valueOf(input.length() * 3)), "baigt")); // 上述结果为 2 System.out.println(doFunction(((Function<String, Integer>) (input -> { System.out.println("notcompose:"+input); return Integer.valueOf(input)+1; })).compose(input -> { System.out.println("compose:"+input); return String.valueOf(Integer.valueOf(input)*3); }), "22")); // 上述结果为 67 

составляют первую часть выполняется, в описанном выше примере, подвергают дальнейшей обработке в соответствии с входными параметрами, а затем передаются в вызывающую специально в качестве входного параметра.

котировка

Указанная ранее ссылка и метода строительства привели два вида ссылок на самом деле построен особым способ ведения. Специфическое описание Что касается официальной документации «Виды Методы Ссылки» раздела.

вид пример
Имя статических методов класса :: Строка :: valueOf
Примеры способа экземпляра объекта :: doctor1 :: тонированное отдых
Имя класса :: методы экземпляра Строка :: toUpperCase
Имя класса :: новая (строительство ссылка) Строка :: новый

Статические ссылки

  • Использование класса
    public static String doStaticReference(Function<Integer,String> function, Integer input) { return function.apply(www.zhenghongyule.com input); } 
  • примеров
doStaticReference(String::valueOf,123456);

Примеры ссылок на объекты метод экземпляра

  • Использование класса
class Doctor{
    String name;
    String interest;
    public Doctor(String name, String interest) { this.name = name; this.interest =www.dajuhezc.cn  interest; } public String getStringInstance(){ return new String(name); } } 
  • примеров
Doctor doctor1=new Doctor("baigt007","java"www.huizhonggjzc.cn);
        Supplier<String> instance = doctor1::getInterest;

Примеры стандартного метода класса

  • Использование класса
    public static String doMethodReference(Function<String,String> function, String input) { return function.apply(input); } 
  • примеров
doMethodReference(String::toUpperCase,www.feishenbo.cn"baigt");O

Эталонная конфигурация

  • примеров
Supplier<String> stringInstance = String::new;

эпилог

Выше личный опыт, несовершенны, пожалуйста, поправьте меня.

рекомендация

отwww.cnblogs.com/laobeipai/p/12068826.html