内容目录
Java8 常用函数式接口及例子
使用案例 | Lambda表达形式 | 函数式接口 |
---|---|---|
布尔表达式 | (List<String> list) -> list.isEmpty() |
Predicate<List<String>> |
创建对象 | () -> new Apple() |
Supplier<Apple> |
消费对象 | (Apple a) -> System.out.println(a.toString()) |
Consumer<Apple> |
对象转换 | (String s) -> s.length() |
或者 |
合并对象 | (int a, int b) -> a * b |
IntBinaryOperator |
比较对象 | (int a, int b) -> a - b |
或者 或者 |
Java8Testpackage com.smile.zhou;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.IntBinaryOperator;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class Java8Test {
@Test
void testPredicate() {
List<Character> characters = Arrays.asList('A', 'b', 'C', 'd', 'E', 'f');
Assertions.assertTrue(characters.stream().filter(Character::isUpperCase).collect(Collectors.toSet()).containsAll(Arrays.asList('A', 'C', 'E')));
Assertions.assertTrue(characters.stream().filter(Character::isLowerCase).collect(Collectors.toSet()).containsAll(Arrays.asList('b', 'd', 'f')));
}
@Test
void testSupplier() {
class X {
}
Supplier<X> supplier = () -> new X();
X x1 = supplier.get();
X x2 = supplier.get();
System.out.println(x1);
System.out.println(x2);
}
@Test
void testConsumer() {
List<Character> characters = Arrays.asList('A', 'b', 'C', 'd', 'E', 'f');
characters.forEach(System.out::println);
}
@Test
void testBinaryOperator() {
IntBinaryOperator add = (x, y) -> x + y;
IntBinaryOperator sub = (x, y) -> x - y;
calc("+", add);
calc("-", sub);
calc("*", (int x, int y) -> x * y);
calc("/", (int x, int y) -> x / y);
}
private void calc(String op, IntBinaryOperator operator) {
int a = 2, b = 1;
System.out.println(String.format("%d %s %d = %d", a, op, b, operator.applyAsInt(a, b)));
}
@Test
void testComparator() {
List<Character> characters = Arrays.asList('A', 'b', 'C', 'd', 'E', 'f');
System.out.println("顺序:" + Arrays.toString(characters.stream().sorted().toArray()));
System.out.println("逆序:" + Arrays.toString(characters.stream().sorted(Comparator.reverseOrder()).toArray()));
}
}
这里只是简单的做个笔记,方便以后查阅。
1 条评论
() -> new X()
一般可以简写为X::new
。同样地,类似于
(String s) -> s.length()
这样纯粹的方法调用也可以简写为String::length
。撰写评论