1、函数式接口
- Predicate<T>
boolean test (T t)
Checks a condition and returns a boolean value as result
In filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) as argument.
- Consumer<T>
void accept(T t)
Operation that takes an argument but returns nothing
In forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection or stream.
- Function<T,R>
R apply(T t)
Functions that take an argument and return a result
In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result.
- Supplier<T>
T get()
Operation that returns a value to the caller (the returned value could be same or different values) In generate() method in java.util.stream.Stream to create an infinite stream of elements.
2.例子
- 这是包含Stream,function interface,lambda的例子:
Stream.of("hello", "world")
.filter(str -> str.startsWith("h")) //Predicate Interface
.forEach(System.out::println); //Consumer Interface
- Predicate的例子
Listing 5-1. PredicateTest.java
import java.util.function.Predicate;
public class PredicateTest {
public static void main(String []args) {
Predicate<String> nullCheck = arg -> arg != null; // return true or false;
Predicate<String> emptyCheck = arg -> arg.length() > 0; // return true or false;
Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); //return true or false
String helloStr = "hello";
System.out.println(nullAndEmptyCheck.test(helloStr)); //Predicate interface
String nullStr = null;
System.out.println(nullAndEmptyCheck.test(nullStr)); //Predicate interface
}
}
This program prints:
true
false
- Predicate和Consumer
Listing 5-2. RemoveIfMethod.java
import java.util.List;
import java.util.ArrayList;
public class RemoveIfMethod {
public static void main(String []args) {
List<String> greeting = new ArrayList<>();
greeting.add("hello");
greeting.add("world");
greeting.removeIf(str -> !str.startsWith("h")); //predicate
greeting.forEach(System.out::println); //comsumer
}
}
print:
hello
world
- Consumer调用accept
Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());
printUpperCase.accept("hello");
// prints: HELLO
- Consumer调用foreach消费
Listing 5-3. ConsumerUse.java
import java.util.stream.Stream;
import java.util.function.Consumer;
class ConsumerUse {
public static void main(String []args) {
Stream<String> strings = Stream.of("hello", "world");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
}
}
This program prints:
hello
world
- Function里有map传值
Listing 5-4. FunctionUse.java
import java.util.Arrays;
public class FunctionUse {
public static void main(String []args) {
Arrays.stream("4, -9, 16".split(", "))
.map(Integer::parseInt)
.map(i -> (i < 0) ? -i : i)
.forEach(System.out::println);
}
}
This program prints:
4
9
16
- Function调用apply()
Function<String, Integer> strLength = str -> str.length();
System.out.println(strLength.apply("supercalifragilisticexpialidocious"));
// prints: 34
- Function和map()
Listing 5-5. CombineFunctions.java
import java.util.Arrays;
import java.util.function.Function;
public class CombineFunctions {
public static void main(String []args) {
Function<String, Integer> parseInt = Integer::parseInt;
Function<Integer, Integer> absInt = Math::abs;
Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt);
Arrays.stream("4, -9, 16".split(", "))
.map(parseAndAbsInt) //map 只是在stream里传递元素,调用foreach
.forEach(System.out::println);
}
}
Hence the code prints the elements as they are, i.e., the
values 4, -9, and 16 in separate lines.
- random::nextBoolean 返回随机的true or false
Listing 5-6. GenerateBooleans.java
import java.util.stream.Stream;
import java.util.Random;
class GenerateBooleans {
public static void main(String []args) {
Random random = new Random();
Stream.generate(random::nextBoolean)//true or false
.limit(2)
.forEach(System.out::println);
}
}
- Supplier调用get
Supplier<String> currentDateTime = () -> LocalDateTime.now().toString();
System.out.println(currentDateTime.get()); //Supplier 调用get()