You can now write a method as a Function in a lambda expression. Let's do it for the time being.
reference Official Reference
Function.java
package functionPractice;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* To practice function-interface
*
* @author me
*
*/
public class FunctionPractice {
/**
* main
*
* @param args
*/
public static void main(String[] args) {
try {
run();
} catch (NumberFormatException e) {
echo.accept("・ Ω ・ v");
}
}
/**
* run
*
* @throws NumberFormatException if conversion to numeric number is impossible.
*/
private static void run() throws NumberFormatException {
generate.get().stream().filter(Objects::nonNull).map(toString.andThen(add3).andThen(toInteger)).forEach(echo);
echo.accept(join.apply(generate.get()));
List<Integer> list = generate.get().stream().map(toInteger).collect(Collectors.toList());
echo.accept(list);
echo.accept(sum.apply(list));
}
/** Output */
static Consumer<Object> echo = v -> System.out.println(v);
/** Generate */
static Supplier<List<String>> generate = () -> Arrays.asList(null, "1", "2", "3");
/** Object to String */
static Function<Object, String> toString = v -> String.valueOf(v);
/** Object to Integer */
static Function<Object, Integer> toInteger = v -> Integer
.parseInt(Optional.ofNullable(v).orElse("1").toString());
/** Add "3" */
static UnaryOperator<String> add3 = v -> v + "3";
/** Join comma */
static Function<List<String>, String> join = v -> v.stream().filter(Objects::nonNull).collect(Collectors.joining(","));
/** Sum integer list */
static Function<List<Integer>, Integer> sum = v -> v.stream().filter(Objects::nonNull)
.collect(Collectors.summingInt(Integer::intValue));
}
Just declare Function <argument, return value>
and write whatever process you like.
Well, there are many other things, but they were officially referred to.
What you usually write with methods can be written with Funtion The number of lines will be reduced and it will be easier to see.
The difficulty is that javaDoc is hard to see?
Even so, it will be insanely smart, right?
Recommended Posts