您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
二周 发布于2020年04月07日 22:36 最近更新于 2020年04月26日 17:01

原创 Java8 函数式接口

2939 次浏览 读完需要≈ 9 分钟 Java

内容目录

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()

Function<String,Integer>

或者ToIntFunction<String>

合并对象 (int a, int b) -> a * b IntBinaryOperator
比较对象 (int a, int b) -> a - b

Comparator<Apple>

或者BiFunction<Integer, Integer, Integer>

或者 ToIntBiFunction<Integer, Integer>

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()));
	}

}

这里只是简单的做个笔记,方便以后查阅。

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

1 条评论

Ready · 3年前

() -> new X() 一般可以简写为 X::new

同样地,类似于 (String s) -> s.length() 这样纯粹的方法调用也可以简写为 String::length

0 0 0

撰写评论