[Java] Functional interface / lambda expression

What is a lambda expression?

If you don't use a lambda expression

public class MethodRefUnuse {
//Output string contents with bracket
  public void walkArray(String[] data) {
    for (var value : data) {
      System.out.printf("[%s]\n", value);
    }
  }
}
//Output the contents of the character string array data in order
public class MethodRefUnuseBasic {

  public static void main(String[] args) {
    var data = new String[] { "Spring is Akebono", "Summer is night", "Autumn is dusk" };
    var un = new MethodRefUnuse();
    un.walkArray(data); //[Spring is Akebono][Summer is night][Autumn is dusk]
  }
}

Method reference

MethodRefUnuse.java


public class MethodRefUse {

//Make it possible to receive the processing method of array elements by method reference
  //In the argument output"Refer to a method that receives an argument as a String type and has a return value of void"To pass

  public void walkArray(String[] data, Output output) {
    for (var value : data) {
      output.print(value);
    }
  }
//Method corresponding to Output type (enclose character string with bracket)
  //The actual state of the print method defined in the functional interface is the addQuote method.
  static void addQuote(String value) {
    System.out.printf("[%s]\n", value);
  }
}

Output.java


//A method type that takes a String type argument and returns a void method type
@FunctionalInterface
public interface Output {
  void print(String str);
}

MethodRefUnuseBasic.java


public class MethodRefUseBasic {

  public static void main(String[] args) {
    var data = new String[] {"Spring is Akebono", "Summer is night", "Autumn is dusk"};
    var u = new MethodRefUse();
    //Pass the method reference to the walkArray method
    u.walkArray(data, MethodRefUse::addQuote);
  }
}

Replace method

//Counter class that counts strings
public class Counter {
  private int result = 0;

  public int getResult() {
    return this.result;
  }

  public void addLength(String value) {
    this.result += value.length();
  }
}
public class CounterBasic {

  public static void main(String[] args) {
    var data = new String[] {"Spring is Akebono", "Summer is night", "Autumn is dusk"};
    var u = new MethodRefUse();
    var c = new Counter();
    //The addLength method of the Counter class adds the string length of value to the result field
    u.walkArray(data, c::addLength);
    System.out.println(c.getResult());
  }
}

Lambda expression appears here

//walkArray method argument Consumer interface
//Consumer is a no-return method that takes a T-type argument and performs some processing
import java.util.function.Consumer;

public class MethodLambda {

  public void walkArray(String[] data, Consumer<String> output) {
    for (var value : data) {
      output.accept(value);
    }
  }
}

public class MethodLambdaBasic {

  public static void main(String[] args) {
    var data = new String[] { "Spring is Akebono", "Summer is night", "Autumn is dusk" };
    var ml = new MethodLambda();
    ml.walkArray(data, (String value) -> {
      System.out.printf("[%s]\n", value);
    });
  }
}

Easier lambda expression

Proper use with anonymous classes


import java.util.function.Consumer;

public class MethodLambdaBasic {

  public static void main(String[] args) {
    var data = new String[] { "Spring is Akebono", "Summer is night", "Autumn is dusk" };
    var ml = new MethodLambda();

    ml.walkArray(data, new Consumer<String>() {
      @Override
      public void accept(String value) {
        System.out.printf("[%s]\n", value);
      }
    });

     ml.walkArray(data, (String value) -> System.out.printf("[%s]\n", value));
     ml.walkArray(data, (value) -> System.out.printf("[%s]\n", value));
     ml.walkArray(data, value -> System.out.printf("[%s]\n", value));
  }
}

Lambda expression collection framework method example

** replaceAll method **

//Extract only the first 3 characters and output 2 or less characters as they are
import java.util.ArrayList;
import java.util.Arrays;

public class CollReplace {

  public static void main(String[] args) {
    var list = new ArrayList<String>(
        Arrays.asList("Neko", "Inu", "Niwatori"));
    list.replaceAll(v -> {
      if (v.length() < 3) {
        return v;
      } else {
        return v.substring(0, 3);
      }
    });
    System.out.println(list); //[Nek, Inu, Niw]
  }
}
//Add key acronym to map value
import java.util.HashMap;
import java.util.Map;

public class CollReplaceMap {

  public static void main(String[] args) {
    var map = new HashMap<String, String>(
      Map.of("cat", "Cat", "dog", "Dog", "bird", "Bird"));
    map.replaceAll((k, v) -> k.charAt(0) + v);
    System.out.println(map); //{cat=c cat, dog=d dog, bird=b Tori}
  }
}

** removeIf method **

//Delete all strings of 5 or more characters
import java.util.ArrayList;
import java.util.Arrays;

public class CollRemove {

  public static void main(String[] args) {
    var list = new ArrayList<String>(
      Arrays.asList("rose", "Tulips", "Morning glory", "Hyacinth"));
    list.removeIf(v -> v.length() > 4);
    System.out.println(list); //[rose",Morning glory]
  }
}

** compute method **

import java.util.HashMap;
import java.util.Map;

//Add the first character of the key to the value (compute/computeIfPresent)
public class CollCompute {
  public static String trans(String key, String value) {
    return key.charAt(0) + value;
  }
//Set the key itself to the value (computeIfAbsent)
  public static String trans(String key) {
    return key;
  }

  public static void main(String[] args) {
    var map = new HashMap<String, String>(Map.of("orange", "Mandarin orange"));

//compute
      map.compute("orange", CollCompute::trans);
      map.compute("melon", CollCompute::trans);
      System.out.println(map); //{orange = o mandarin orange, melon=mnull}

/*
computeIfPresent: Processing is executed only when the key exists
    map.computeIfPresent("orange", CollCompute::trans);
    map.computeIfPresent("melon", CollCompute::trans);
    System.out.println(map); //{orange = o mandarin orange}
*/

/*computeIfAbsent: Process only those that do not have a key
    map.computeIfAbsent("orange", CollCompute::trans);
    map.computeIfAbsent("melon", CollCompute::trans);
    System.out.println(map); //{orange = mandarin orange, melon=melon}
*/
  }
}

merge method

//Concatenate values separated by commas when duplicate values
import java.util.HashMap;
import java.util.Map;

public class CollMerge {
    public static String concat(String v1, String v2) {
        if(v2 == "") {return null;}
        return v1 + "," + v2;
    }
    public static void main(String[] args) {
        var map = new HashMap<String, String>(Map.of("cat", "three colored cat"));
        map.merge("dog", "Pomera An", CollMerge::concat);
        map.merge("cat", "Persian", CollMerge::concat);
        map.merge("dog", "Poodle", CollMerge::concat);
        System.out.println(map); //{dog=Pomera An,Poodle, cat=three colored cat,Persian}

        //Join function(remap)Discards the key itself if returns null
        map.merge("cat", "", CollMerge::concat);
        System.out.println(map); //{dog=Pomera An,Poodle}
    }
}

Recommended Posts

[Java] Functional interface / lambda expression
[Java] Lambda expression
[Java] Functional interface
Java lambda expression
About Java functional interface
java standard functional interface
java neutral lambda expression 1
Java lambda expression variations
Java 8 lambda expression Feature
java lambda expression memo
Java lambda expression [memo]
Studying Java 8 (lambda expression)
Review java8 ~ Lambda expression ~
Java lambda expression again
Java8 stream, lambda expression summary
java (interface)
[java] interface
Java basic learning content 9 (lambda expression)
What is a lambda expression (Java)
About Java interface
Now let's recap the Java lambda expression
Functional interface introduction
[Java] About interface
Hello Java Lambda
About interface, java interface
How to use Java API with lambda expression
Java8 to start now ~ forEach and lambda expression ~
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -
Callable Interface in Java
java learning (conditional expression)
Functional interface review notes
Quarkus saves Java Lambda! ??
Understand Java 8 lambda expressions
JAVA learning history interface
About Java lambda expressions
Introduction to lambda expression
Explain Java 8 lambda expressions
Java learning memo (interface)
Java table expression injection
java regular expression summary
Java Lambda Command Pattern
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Java8 Lambda Expression & Stream Design Pattern Rethinking --Null Object Pattern -
Java8 Lambda expression & Stream design pattern reconsideration --Template Method pattern -
Use Lambda Layers with Java
Advanced inheritance abstract, interface -java
Assign a Java8 lambda expression to a variable and reuse it
JAVA learning history interface inheritance
Try functional type in Java! ①
Check Java9 Interface private methods
[Java] Introduction to lambda expressions
What is a lambda expression?
Memoization recursion with lambda expression
Java8 Lambda Expression & Stream Design Pattern Rethinking --Chain of Responsibility Pattern -
Implement functional quicksort in Java
Access the network interface in Java
Java lambda expressions learned with Comparator
Until the interface implementation becomes lambda
[Introduction to Java] About lambda expressions
Java and first-class functions-beyond functional interfaces-
About Lambda, Stream, LocalDate of Java8