笔记:Java8新特性

(持续更新中)

一. java8 的新特性

1. 速度更快

2. 代码更少(增加了新的语法 Lambda 表达式)

3. 强大的 Stream API

4. 便于并行

5. 最大化减少空指针异常 Optional

其中最为核心的为 Lambda 表达式与 Stream API

// Lambda 表达式
@Test
public void test6(){
	List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
	list.forEach(System.out::println);

	System.out.println("------------------------------------------");

	List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
	list2.forEach(System.out::println);
}

// Stream API
@Test
public void test7(){
	emps.stream()
	.filter((e) -> e.getAge() <= 35)
	.forEach(System.out::println);

	System.out.println("----------------------------------------------");

	emps.stream()
	.map(Employee::getName)
	.limit(3)
	.sorted()
	.forEach(System.out::println);
}

二.  Lambda 表达式

1. Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。

/*
 * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
 * 						    箭头操作符将 Lambda 表达式拆分成两部分:
 * 
 * 左侧:Lambda 表达式的参数列表
 * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
 * 
 * 语法格式一:无参数,无返回值
 * 		() -> System.out.println("Hello Lambda!");
 * 
 * 语法格式二:有一个参数,并且无返回值
 * 		(x) -> System.out.println(x)
 * 
 * 语法格式三:若只有一个参数,小括号可以省略不写
 * 		x -> System.out.println(x)
 * 
 * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
 *		Comparator<Integer> com = (x, y) -> {
 *			System.out.println("函数式接口");
 *			return Integer.compare(x, y);
 *		};
 *
 * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
 * 		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 * 
 * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
 * 		(Integer x, Integer y) -> Integer.compare(x, y);
 * 
 * 上联:左右遇一括号省
 * 下联:左侧推断类型省
 * 横批:能省则省
 * 
 * 二、Lambda 表达式需要“函数式接口”的支持
 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
 * 			 可以检查是否是函数式接口
 */
public class TestLambda2 {
	
	@Test
	public void test1(){
		int num = 0;//jdk 1.7 前,必须是 final
		
		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println("Hello World!" + num);
			}
		};
		
		r.run();
		
		System.out.println("-------------------------------");
		
		Runnable r1 = () -> System.out.println("Hello Lambda!");
		r1.run();
	}
	
	@Test
	public void test2(){
		Consumer<String> con = x -> System.out.println(x);
		con.accept("一条消息!");
	}
	
	@Test
	public void test3(){
		Comparator<Integer> com = (x, y) -> {
			System.out.println("函数式接口");
			return Integer.compare(x, y);
		};
	}
	
	@Test
	public void test4(){
		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	}
	
	@Test
	public void test5(){
//		String[] strs;
//		strs = {"aaa", "bbb", "ccc"};
		
		List<String> list = new ArrayList<>();
		
		show(new HashMap<>());
	}

	public void show(Map<String, Integer> map){
		
	}
	
	//需求:对一个数进行运算
	@Test
	public void test6(){
		Integer num = operation(100, (x) -> x * x);
		System.out.println(num);
		
		System.out.println(operation(200, (y) -> y + 200));
	}
	
	public Integer operation(Integer num, MyFun mf){
		return mf.getValue(num);
	}
}

2. 四大内置核心函数式接口

/*
 * Java8 内置的四大核心函数式接口
 * 
 * Consumer<T> : 消费型接口
 * 		void accept(T t);
 * 
 * Supplier<T> : 供给型接口
 * 		T get(); 
 * 
 * Function<T, R> : 函数型接口
 * 		R apply(T t);
 * 
 * Predicate<T> : 断言型接口
 * 		boolean test(T t);
 * 
 */
public class TestLambda3 {
	
	//Predicate<T> 断言型接口:
	@Test
	public void test4(){
		List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
		List<String> strList = filterStr(list, (s) -> s.length() > 3);
		
		for (String str : strList) {
			System.out.println(str);
		}
	}
	
	//需求:将满足条件的字符串,放入集合中
	public List<String> filterStr(List<String> list, Predicate<String> pre){
		List<String> strList = new ArrayList<>();
		
		for (String str : list) {
			if(pre.test(str)){
				strList.add(str);
			}
		}
		
		return strList;
	}
	
	//Function<T, R> 函数型接口:
	@Test
	public void test3(){
		String newStr = strHandler("\t\t\t 一条消息   ", (str) -> str.trim());
		System.out.println(newStr);
		
		String subStr = strHandler("一条新消息", (str) -> str.substring(2, 5));
		System.out.println(subStr);
	}
	
	//需求:用于处理字符串
	public String strHandler(String str, Function<String, String> fun){
		return fun.apply(str);
	}
	
	//Supplier<T> 供给型接口 :
	@Test
	public void test2(){
		List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
		
		for (Integer num : numList) {
			System.out.println(num);
		}
	}
	
	//需求:产生指定个数的整数,并放入集合中
	public List<Integer> getNumList(int num, Supplier<Integer> sup){
		List<Integer> list = new ArrayList<>();
		
		for (int i = 0; i < num; i++) {
			Integer n = sup.get();
			list.add(n);
		}
		
		return list;
	}
	
	//Consumer<T> 消费型接口 :
	@Test
	public void test1(){
		happy(10000, (m) -> System.out.println("大宝剑,每次消费:" + m + "元"));
	} 
	
	public void happy(double money, Consumer<Double> con){
		con.accept(money);
	}
}

三. 方法引用于构造器引用

/*
 * 一、方法引用:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用
 * 			  (可以将方法引用理解为 Lambda 表达式的另外一种表现形式)
 * 
 * 1. 对象的引用 :: 实例方法名
 * 
 * 2. 类名 :: 静态方法名
 * 
 * 3. 类名 :: 实例方法名
 * 
 * 注意:
 * 	 ①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
 * 	 ②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,
 * 	  格式: ClassName::MethodName
 * 
 * 二、构造器引用 :构造器的参数列表,需要与函数式接口中参数列表保持一致!
 * 
 * 1. 类名 :: new
 * 
 * 三、数组引用
 * 
 * 	类型[] :: new;
 * 
 * 
 */
public class TestMethodRef {
	//数组引用
	@Test
	public void test8(){
		Function<Integer, String[]> fun = (args) -> new String[args];
		String[] strs = fun.apply(10);
		System.out.println(strs.length);
		
		System.out.println("--------------------------");
		
		Function<Integer, Employee[]> fun2 = Employee[] :: new;
		Employee[] emps = fun2.apply(20);
		System.out.println(emps.length);
	}
	
	//构造器引用
	@Test
	public void test7(){
		Function<String, Employee> fun = Employee::new;
		
		BiFunction<String, Integer, Employee> fun2 = Employee::new;
	}
	
	@Test
	public void test6(){
		Supplier<Employee> sup = () -> new Employee();
		System.out.println(sup.get());
		
		System.out.println("------------------------------------");
		
		Supplier<Employee> sup2 = Employee::new;
		System.out.println(sup2.get());
	}
	
	//类名 :: 实例方法名
	@Test
	public void test5(){
		BiPredicate<String, String> bp = (x, y) -> x.equals(y);
		System.out.println(bp.test("abcde", "abcde"));
		
		System.out.println("-----------------------------------------");
		
		BiPredicate<String, String> bp2 = String::equals;
		System.out.println(bp2.test("abc", "abc"));
		
		System.out.println("-----------------------------------------");
		
		
		Function<Employee, String> fun = (e) -> e.show();
		System.out.println(fun.apply(new Employee()));
		
		System.out.println("-----------------------------------------");
		
		Function<Employee, String> fun2 = Employee::show;
		System.out.println(fun2.apply(new Employee()));
		
	}
	
	//类名 :: 静态方法名
	@Test
	public void test4(){
		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
		
		System.out.println("-------------------------------------");
		
		Comparator<Integer> com2 = Integer::compare;
	}
	
	@Test
	public void test3(){
		BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
		System.out.println(fun.apply(1.5, 22.2));
		
		System.out.println("--------------------------------------------------");
		
		BiFunction<Double, Double, Double> fun2 = Math::max;
		System.out.println(fun2.apply(1.2, 1.5));
	}

	//对象的引用 :: 实例方法名
	@Test
	public void test2(){
		Employee emp = new Employee(101, "张三", 18, 9999.99);
		
		Supplier<String> sup = () -> emp.getName();
		System.out.println(sup.get());
		
		System.out.println("----------------------------------");
		
		Supplier<String> sup2 = emp::getName;
		System.out.println(sup2.get());
	}
	
	@Test
	public void test1(){
		PrintStream ps = System.out;
		Consumer<String> con = (str) -> ps.println(str);
		con.accept("Hello World!");
		
		System.out.println("--------------------------------");
		
		Consumer<String> con2 = ps::println;
		con2.accept("Hello Java8!");
		
		Consumer<String> con3 = System.out::println;
	}
	
}

四. Stream API

1. 创建 Stream

//1. 创建 Stream
@Test
public void test1(){
	//1. Collection 提供了两个方法  stream() 与 parallelStream()
	List<String> list = new ArrayList<>();
	Stream<String> stream = list.stream(); //获取一个顺序流
	Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

	//2. 通过 Arrays 中的 stream() 获取一个数组流
	Integer[] nums = new Integer[10];
	Stream<Integer> stream1 = Arrays.stream(nums);

	//3. 通过 Stream 类中静态方法 of()
	Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);

	//4. 创建无限流
	//迭代
	Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
	stream3.forEach(System.out::println);

	//生成
	Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
	stream4.forEach(System.out::println);

}

2. Stream 筛选与切片

//2. 中间操作
List<Employee> emps = Arrays.asList(
		new Employee(102, "李四", 59, 6666.66),
		new Employee(101, "张三", 18, 9999.99),
		new Employee(103, "王五", 28, 3333.33),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(105, "田七", 38, 5555.55)
		);

/*
	  筛选与切片
		filter——接收 Lambda , 从流中排除某些元素。
		limit——截断流,使其元素不超过给定数量。
		skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
		distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
 */

//内部迭代:迭代操作 Stream API 内部完成
@Test
public void test2(){
	//所有的中间操作不会做任何的处理
	Stream<Employee> stream = emps.stream()
			.filter((e) -> {
				System.out.println("测试中间操作");
				return e.getAge() <= 35;
			});

	//只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
	stream.forEach(System.out::println);
}

//外部迭代
@Test
public void test3(){
	Iterator<Employee> it = emps.iterator();

	while(it.hasNext()){
		System.out.println(it.next());
	}
}

@Test
public void test4(){
	emps.stream()
	.filter((e) -> {
		System.out.println("短路!"); // &&  ||
		return e.getSalary() >= 5000;
	}).limit(3)
	.forEach(System.out::println);
}

@Test
public void test5(){
	emps.parallelStream()
	.filter((e) -> e.getSalary() >= 5000)
	.skip(2)
	.forEach(System.out::println);
}

@Test
public void test6(){
	emps.stream()
	.distinct()
	.forEach(System.out::println);
}

3. 映射

//2. 中间操作
/*
		映射
		map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
		flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
 */
@Test
public void test1(){
	Stream<String> str = emps.stream()
			.map((e) -> e.getName());

	System.out.println("-------------------------------------------");

	List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

	Stream<String> stream = strList.stream()
			.map(String::toUpperCase);

	stream.forEach(System.out::println);

	Stream<Stream<Character>> stream2 = strList.stream()
			.map(TestStreamAPI1::filterCharacter);

	stream2.forEach((sm) -> {
		sm.forEach(System.out::println);
	});

	System.out.println("---------------------------------------------");

	Stream<Character> stream3 = strList.stream()
			.flatMap(TestStreamAPI1::filterCharacter);

	stream3.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str){
	List<Character> list = new ArrayList<>();
	
	for (Character ch : str.toCharArray()) {
		list.add(ch);
	}
	
	return list.stream();
}

4. 排序

/*
sorted()——自然排序
sorted(Comparator com)——定制排序
*/
@Test
public void test2(){
emps.stream()
	.map(Employee::getName)
	.sorted()
	.forEach(System.out::println);

System.out.println("------------------------------------");

emps.stream()
	.sorted((x, y) -> {
		if(x.getAge() == y.getAge()){
			return x.getName().compareTo(y.getName());
		}else{
			return Integer.compare(x.getAge(), y.getAge());
		}
	}).forEach(System.out::println);
}

5. 查找与匹配

//3. 终止操作
/*
		allMatch——检查是否匹配所有元素
		anyMatch——检查是否至少匹配一个元素
		noneMatch——检查是否没有匹配的元素
		findFirst——返回第一个元素
		findAny——返回当前流中的任意元素
		count——返回流中元素的总个数
		max——返回流中最大值
		min——返回流中最小值
 */
@Test
public void test1(){
	boolean bl = emps.stream()
			.allMatch((e) -> e.getStatus().equals(Status.BUSY));

	System.out.println(bl);

	boolean bl1 = emps.stream()
			.anyMatch((e) -> e.getStatus().equals(Status.BUSY));

	System.out.println(bl1);

	boolean bl2 = emps.stream()
			.noneMatch((e) -> e.getStatus().equals(Status.BUSY));

	System.out.println(bl2);
}

@Test
public void test2(){
	Optional<Employee> op = emps.stream()
			.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
			.findFirst();

	System.out.println(op.get());

	System.out.println("--------------------------------");

	Optional<Employee> op2 = emps.parallelStream()
			.filter((e) -> e.getStatus().equals(Status.FREE))
			.findAny();

	System.out.println(op2.get());
}

@Test
public void test3(){
	long count = emps.stream()
			.filter((e) -> e.getStatus().equals(Status.FREE))
			.count();

	System.out.println(count);

	Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.max(Double::compare);

	System.out.println(op.get());

	Optional<Employee> op2 = emps.stream()
			.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));

	System.out.println(op2.get());
}

//注意:流进行了终止操作后,不能再次使用
@Test
public void test4(){
	Stream<Employee> stream = emps.stream()
			.filter((e) -> e.getStatus().equals(Status.FREE));

	long count = stream.count();

	stream.map(Employee::getSalary)
	.max(Double::compare);
}

6. 归约与收集

/*
归约
reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
 */
@Test
public void test1(){
	List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

	Integer sum = list.stream()
			.reduce(0, (x, y) -> x + y);

	System.out.println(sum);

	System.out.println("----------------------------------------");

	Optional<Double> op = employees.stream()
			.map(Employee::getSalary)
			.reduce(Double::sum);

	System.out.println(op.get());
}

//collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
@Test
public void test3(){
	List<String> list = employees.stream()
			.map(Employee::getName)
			.collect(Collectors.toList());

	list.forEach(System.out::println);

	System.out.println("----------------------------------");

	Set<String> set = employees.stream()
			.map(Employee::getName)
			.collect(Collectors.toSet());

	set.forEach(System.out::println);

	System.out.println("----------------------------------");

	HashSet<String> hs = employees.stream()
			.map(Employee::getName)
			.collect(Collectors.toCollection(HashSet::new));

	hs.forEach(System.out::println);
}

@Test
public void test4(){
	// 最大
	Optional<Double> max = employees.stream()
			.map(Employee::getSalary)
			.collect(Collectors.maxBy(Double::compare));

	System.out.println(max.get());

	// 最小
	Optional<Employee> op = employees.stream()
			.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

	System.out.println(op.get());

	// 合计
	Double sum = employees.stream()
			.collect(Collectors.summingDouble(Employee::getSalary));

	System.out.println(sum);

	// 平均值
	Double avg = employees.stream()
			.collect(Collectors.averagingDouble(Employee::getSalary));

	System.out.println(avg);

	// 个数
	Long count = employees.stream()
			.collect(Collectors.counting());

	System.out.println(count);

	System.out.println("--------------------------------------------");

	// 另外方式查出来
	DoubleSummaryStatistics dss = employees.stream()
			.collect(Collectors.summarizingDouble(Employee::getSalary));

	System.out.println(dss);
}

//分组
@Test
public void test5(){
	Map<Status, List<Employee>> map = employees.stream()
			.collect(Collectors.groupingBy(Employee::getStatus));

	System.out.println(map);
}

//多级分组
@Test
public void test6(){
	Map<Status, Map<String, List<Employee>>> map = employees.stream()
			.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
				if(e.getAge() >= 60)
					return "老年";
				else if(e.getAge() >= 35)
					return "中年";
				else
					return "成年";
			})));

	System.out.println(map);
}

//分区
@Test
public void test7(){
	Map<Boolean, List<Employee>> map = employees.stream()
			.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

	System.out.println(map);
}

//
@Test
public void test8(){
	// joining 第一个参数:分隔符,第二个参数,开头分隔符,第三个参数,最后分隔符
	String str = employees.stream()
			.map(Employee::getName)
			.collect(Collectors.joining("," , "----", "----"));

	System.out.println(str);
}

@Test
public void test9(){
	Optional<Double> sum = employees.stream()
			.map(Employee::getSalary)
			.collect(Collectors.reducing(Double::sum));

	System.out.println(sum.get());
}

猜你喜欢

转载自blog.csdn.net/qq_36797286/article/details/81533938