PROGRAMMING     CLIMBING

  minte9
reminder




Last update:   29-10-2021

STATIC METHODS

p 77 Another new change in Java 8 was static methods in interfaces.
 
/**
 * It's always better to put related methods in the same place.
 * Static methods are allowed in interfaces (Java 8).
 */

package com.minte9.lambdas.static_methods;

import java.util.function.BinaryOperator;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;

public class StaticMethod {
  public static void main(String[] args) {
      
    int sum = MyStream.of(1, 2, 3)
      .reduce(0, (acc, x) -> acc + x)
    ;
    assertEquals(6, sum); // pass
  }
}

abstract interface MyStream<T> extends Stream<T> {
  
    @SafeVarargs 
    @SuppressWarnings("varargs")

    static <T> Stream<T> of(T... values) { // Look Here
        return Stream.of(values);
    }

    abstract T reduce(T arg0, BinaryOperator<T> arg1);
}

Method Reference

p 83 The syntax when lambdas call methods on its parameter is named method reference.
 
/**
 * It is very common to use a lambdas that call methods on its parameter.
 * There is an abbreviated syntax for this, called ...
 * method reference.
 * 
 * The standard form of method reference is ...
 * Classname::methodName
 * 
 * The code is not only more shorter ...
 * but also a lot easier to read.
 */
package com.minte9.lambdas.static_methods;

import java.util.Arrays;
import java.util.List;

public class MethodReference {
  public static void main(String[] args) {
      
    List<String> myList = Arrays.asList("a", "b", "c");

    myList.stream()
      .map(x -> x + x)
      .map(String::toUpperCase)
      .forEach(System.out::println); 
        // AA BB CC
  }
}

Questions     github Lambdas
Single Responsibility
        A B C D E F
🔔
1/1