Java8新特性

一、Lambda表达式

Lambda表达式初体验

创建一个新的线程,指定线程要执行的任务

public static void main(String[] args) {
	//*斜体样式**开启一个新的线程*
	new Thread(new Runnable() {
		@Override
		public void run() {
		System.out.println("新线程中执行的代码 :
		"+Thread.currentThread().getName());
		}
		}).start();
	System.out.println("主线程中的代码:" + Thread.currentThread().getName());
}

Lambda表达式写法:

new Thread(
() -> { System.out.println("新线程Lambda表达式..."
+Thread.currentThread().getName()); })
.start();

Lambda表达式是一个匿名函数,可以理解为一段可以传递的代码。
Lambda表达式的优点:简化了匿名内部类的使用,语法更加简单。
匿名内部类语法冗余,体验了Lambda表达式后,发现Lambda表达式是简化匿名内
名内部类的一种方式。

Lambda的语法规则

(参数类型 参数名称) -> { 代码体; }

格式说明:

  • (参数类型 参数名称):参数列表
  • {代码体;} :方法体
  • -> :箭头,分割参数列表和方法体

无参无返回值的Lambda

public interface UserService {
void show();
}
public class Demo {
	public static void main(String[] args) {
	
		goShow(new UserService() {
		@Override
		public void show() {
		System.out.println("show 方法执行了...");
		} 
		System.out.println("----------");
		//Lambda
		goShow(() -> { System.out.println("Lambda show 方法执行了..."); });
		}

	public static void goShow(UserService userService){
		userService.show();
}
}

有参且有返回值的Lambda表达式

创建一个Person对象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
	private String name;
	private Integer age;
	private Integer height;
}

然后我们在List集合中保存多个Person对象,然后对这些对象做根据age排序操作

public static void main(String[] args) {
	List<Person> list = new ArrayList<>();
	list.add(new Person("周杰伦",33,175));
	list.add(new Person("刘德华",43,185));
	list.add(new Person("周星驰",38,177));
	list.add(new Person("郭富城",23,170));
	
	/*Collections.sort(list, new Comparator<Person>() {
	@Override
	public int compare(Person o1, Person o2) {
	return o1.getAge()-o2.getAge();
	}
	});
	for (Person person : list) {
	System.out.println(person);
	}*/
	
	//Lambda
	Collections.sort(
	list,(Person o1,Person o2) -> {return o1.getAge() - o2.getAge();}
	);
	for (Person person : list) {
	System.out.println(person);
}
}

@FunctionalInterface注解

/**
* @FunctionalInterface
* 这是一个标志注解,被该注解修饰的接口只能声明一个抽象方法
*/
@FunctionalInterface
public interface UserService {
	void show();
}

Lambda表达式的原理

匿名内部类在编译的时候会产生一个class文件。

Lambda表达式在程序运行的时候会形成一个类:

  1. 在类中新增了一个方法,这个方法的方法体就是Lambda表达式中的代码
  2. 还会形成一个匿名内部类,实现接口,重写抽象方法
  3. 在接口中重写方法会调用新生成的方法

Lambda表达式的省略写法

在lambda表达式的标准写法基础上,可以使用省略写法的规则为:

  1. 小括号内的参数类型可以省略
  2. 如果小括号内有且仅有一个参数,则小括号可以省略
  3. 如果大括号内有且仅有一个语句,可以同时省略大括号、return 关键字、语句分号。

Lambda表达式的使用前提

Lambda表达式的语法是非常简洁的,但是Lambda表达式不是随便使用的,使用时有几个条件要特别注意

  1. 方法的参数或局部变量类型必须为接口才能使用Lambda
  2. 接口中有且仅有一个抽象方法(@FunctionalInterface)

Lambda和匿名内部类的对比

Lambda和匿名内部类的对比

  1. 所需类型不一样
    匿名内部类的类型可以是 类,抽象类,接口
    Lambda表达式需要的类型必须是接口
  2. 抽象方法的数量不一样
    匿名内部类所需的接口中的抽象方法的数量是随意的
    Lambda表达式所需的接口中只能有一个抽象方法
  3. 实现原理不一样
    匿名内部类是在编译后形成一个class
    Lambda表达式是在程序运行的时候动态生成class

接口中新增的方法

JDK8之后对接口做了增加,接口中可以有 默认方法静态方法

默认方法

interface 接口名{
	修饰符 default 返回值类型 方法名{
		方法体;
	}
}

接口中的默认方法有两种使用方式

  1. 实现类直接调用接口的默认方法
  2. 实现类重写接口的默认方法

静态方法

interface 接口名{
	修饰符 static 返回值类型 方法名{
		方法体;
	}
}

接口中的静态方法在实现类中是不能被重写的,调用的话只能通过接口类型来实现。

两者的区别介绍:

  1. 默认方法通过实例调用,静态方法通过接口名调用
  2. 默认方法可以被继承,实现类可以直接调用接口默认方法,也可以重写接口默认方法
  3. 静态方法不能被继承,实现类不能重写接口的静态方法,只能使用接口名调用

函数式接口

Lambda表达式的前提是需要有函数式接口,而Lambda表达式使用时不关心接口名,抽象方法名,只关心抽象方法的参数列表和返回值类型。JDK中提供了大量常用的函数式接口,主要是在 java.util.function 包中。

Supplier:无参有返回值的接口,Lambda表达式需要提供一个返回数据的类型。用来生产数据

@FunctionalInterface
public interface Supplier<T> {
	/**
	* Gets a result.
	*
	* @return a result
	*/
	T get();
}

使用

public class SupplierTest {
	public static void main(String[] args) {
		fun1(()->{
		int arr[] = {22,33,55,66,44,99,10};
		// 计算出数组中的最大值
		Arrays.sort(arr);
		return arr[arr.length-1];
		});
	}
	private static void fun1(Supplier<Integer> supplier){
		// get() 是一个无参的有返回值的 抽象方法
		Integer max = supplier.get();
		System.out.println("max = " + max);
	}
}

Consumer:有参无返回值的接口, 用来消费数据,使用的时候需要指定一个泛型来定义参数类型

@FunctionalInterface
public interface Consumer<T> {
	/**
	* Performs this operation on the given argument.
	*
	* @param t the input argument
	*/
	void accept(T t);
}

使用:将输入的数据统一转换为小写输出

public class ConsumerTest {
	public static void main(String[] args) {
		test(msg -> {
		System.out.println(msg + "-> 转换为小写:" + msg.toLowerCase());
		});
	}
	
	public static void test(Consumer<String> consumer){
		consumer.accept("Hello World");
	}
}

默认方法:andThen()

如果一个方法的参数和返回值全部是Consumer类型,消费一个数据的时候,先做一个操作,然后再做一个操作,实现组合,而这个方法就是Consumer接口中的default方法 andThen 方法。

default Consumer<T> andThen(Consumer<? super T> after) {
	Objects.requireNonNull(after);
	return (T t) -> { accept(t); after.accept(t); };
}

具体操作:

public class ConsumerAndThenTest {
	public static void main(String[] args) {
		test2(
			msg1->{
			System.out.println(msg1 + "-> 转换为小写:" + msg1.toLowerCase());
			},
			msg2->{
			System.out.println(msg2 + "-> 转换为大写:" + msg2.toUpperCase());
			});
	}
	
	public static void test2(Consumer<String> c1,Consumer<String> c2){
		String str = "Hello World";
		//c1.accept(str); // 转小写
		//c2.accept(str); // 转大写
		//c1.andThen(c2).accept(str);
		c2.andThen(c1).accept(str);
}
}

Function:有参有返回值的接口,Function接口是根据一个类型的数据得到另一个类型的数据,有参数有返回值。

@FunctionalInterface
public interface Function<T, R> {
	/**
	* Applies this function to the given argument.
	*
	* @param t the function argument
	* @return the function result
	*/
	R apply(T t);
}

使用:传递进入一个字符串返回一个数字

public class FunctionTest {
	public static void main(String[] args) {
		test(msg ->{return Integer.parseInt(msg);});
	}
	
	public static void test(Function<String,Integer> function){
		Integer apply = function.apply("666");
		System.out.println("apply = " + apply);
	}
}

默认方法:andThen,也是用来进行组合操作。

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
	Objects.requireNonNull(after);
	return (T t) -> after.apply(apply(t));
}
public class FunctionAndThenTest {
	public static void main(String[] args) {
		test(msg ->{
		return Integer.parseInt(msg);
		},msg2->{
		return msg2 * 10;
		});
}
	public static void test(Function<String,Integer>
		f1,Function<Integer,Integer> f2){
		/*Integer i1 = f1.apply("666");
		Integer i2 = f2.apply(i1);*/
		Integer i2 = f1.andThen(f2).apply("666");
		System.out.println("i2:" + i2);
	}
}

Predicate:有参且返回值为Boolean的接口

@FunctionalInterface
public interface Predicate<T> {
	/**
	* Evaluates this predicate on the given argument.
	*
	* @param t the input argument
	* @return {@code true} if the input argument matches the predicate,
	* otherwise {@code false}
	*/
	boolean test(T t);
}
public class PredicateTest {
		public static void main(String[] args) {
			test(msg -> {
			return msg.length() > 3;
			},"HelloWorld");
		}
	
	private static void test(Predicate<String> predicate,String msg){
		boolean b = predicate.test(msg);
		System.out.println("b:" + b);
		}
}

在Predicate中的默认方法提供了逻辑关系操作 and、or、negate、isEquals方法。

方法引用

符号表示: ::
符号说明:双冒号为方法引用运算符,而它所在的表达式被称为 方法引用
应用场景:如果Lambda表达式所要实现的方案,已经有其他方法存在相同的方案,那么则可以使用方法引用。

方法引用在JDK8中使用是相当灵活的,有以下几种形式:

  1. instanceName::methodName 对象::方法名
  2. ClassName::staticMethodName 类名::静态方法
  3. ClassName::methodName 类名::普通方法
  4. ClassName::new 类名::new 调用的构造器
  5. TypeName[]::new String[]::new 调用数组的构造器
public class FunctionRefTest02 {
	public static void main(String[] args) {
		// :: 方法引用 也是JDK8中的新的语法
		printMax(FunctionRefTest02::getTotal);
		}
		
	/**
	* 求数组中的所有元素的和
	*/
	public static void getTotal(int a[]){
		int sum = 0;
		for (int i : a) {
		sum += i;
		}
		System.out.println("数组之和:" + sum);
	}
	
	private static void printMax(Consumer<int[]> consumer){
		int[] a= {10,20,30,40,50,60};
		consumer.accept(a);
	}
}

Stream

Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种数据结构,不保存数据,而是对数据进行加工处理。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。
Stream API能让我们快速完成许多复杂的操作,如筛选、切片、映射、查找、去除重复,统计,匹配和归约。

Stream流的获取方式

根据Collection获取

java.util.Collection 接口中加入了default方法 stream,也就是说Collection接口下的所有的实现都可以通过steam方法来获取Stream流。
Map接口别没有实现Collection接口,但是可以根据Map获取对应的key value的集合。

通过Stream的of方法

在实际开发中我们不可避免的还是会操作到数组中的数据,由于数组对象不可能添加默认方法,所有Stream接口中提供了静态方法of

public static void main(String[] args) {
	Stream<String> a1 = Stream.of("a1", "a2", "a3");
	String[] arr1 = {"aa","bb","cc"};
	Stream<String> arr11 = Stream.of(arr1);
	Integer[] arr2 = {1,2,3,4};
	Stream<Integer> arr21 = Stream.of(arr2);
	arr21.forEach(System.out::println);
	// 注意:基本数据类型的数组是不行的
	int[] arr3 = {1,2,3,4};
	Stream.of(arr3).forEach(System.out::println);
}
Stream常用方法介绍

Stream流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:

终结方法:返回值类型不再是 Stream 类型的方法,不再支持链式调用。本小节中,终结方法包括count 和forEach 方法。
非终结方法:返回值类型仍然是 Stream 类型的方法,支持链式调用。(除了终结方法外,其余方法均为非终结方法。)

Stream注意事项(重要)

  1. Stream只能操作一次
  2. Stream方法返回的是新的流
  3. Stream不调用终结方法,中间的操作不会执行
forEac:用来遍历流中的数据
void forEach(Consumer<? super T> action);

该方法接受一个Consumer接口,会将每一个流元素交给函数处理

public static void main(String[] args) {
	Stream.of("a1", "a2", "a3").forEach(System.out::println);;
}
count:Stream流中的count方法用来统计其中的元素个数
public static void main(String[] args) {
	long count = Stream.of("a1", "a2", "a3").count();
	System.out.println(count);
}
filter:用来过滤数据的,返回符合条件的数据

可以通过filter方法将一个流转换成另一个子集流

Stream<T> filter(Predicate<? super T> predicate);
public static void main(String[] args) {
	Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
	.filter((s)->s.contains("a"))
	.forEach(System.out::println);
}
reduce:如果需要将所有数据归纳得到一个数据,可以使用reduce方法
public static void main(String[] args) {
	Integer sum = Stream.of(4, 5, 3, 9)
	// identity默认值
	// 第一次的时候会将默认值赋值给x
	// 之后每次会将 上一次的操作结果赋值给x y就是每次从数据中获取的元素
	.reduce(0, (x, y) -> {
	System.out.println("x="+x+",y="+y);
		return x + y;
	});
	System.out.println(sum);
	// 获取 最大值
	Integer max = Stream.of(4, 5, 3, 9)
	.reduce(0, (x, y) -> {
		return x > y ? x : y;
	});
	System.out.println(max);
}
concat

如果有两个流,希望合并成为一个流,那么可以使用Stream接口的静态方法concat

Stream结果收集
结果收集到集合中
List<String> list = Stream.of("aa", "bb", "cc","aa")
.collect(Collectors.toList());
System.out.println(list)

`// 收集到 Set集合中
Set<String> set = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toSet());
System.out.println(set);

// 如果需要获取的类型为具体的实现,比如:ArrayList HashSet
ArrayList<String> arrayList = Stream.of("aa", "bb", "cc", "aa")
//.collect(Collectors.toCollection(() -> new ArrayList<>()));
.collect(Collectors.toCollection(ArrayList::new));
System.out.println(arrayList);

HashSet<String> hashSet = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toCollection(HashSet::new));
System.out.println(hashSet);
}
结果收集到数组中

Stream中提供了toArray方法来将结果放到一个数组中,返回值类型是Object[],如果我们要指定返回的类型,那么可以使用另一个重载的toArray(IntFunction f)方法.

对流中数据做分组操作
/**
* 分组计算
*/

// 根据账号对数据进行分组
Map<String, List<Person>> map1 = Stream.of(
	new Person("张三", 18, 175)
	, new Person("李四", 22, 177)
	, new Person("张三", 14, 165)
	, new Person("李四", 15, 166)
	, new Person("张三", 19, 182)
	).collect(Collectors.groupingBy(Person::getName));
map1.forEach((k,v)-> System.out.println("k=" + k +"\t"+ "v=" + v));
System.out.println("-----------");
// 根据年龄分组 如果大于等于18 成年否则未成年
Map<String, List<Person>> map2 = Stream.of(
	new Person("张三", 18, 175)
	, new Person("李四", 22, 177)
	, new Person("张三", 14, 165)
	, new Person("李四", 15, 166)
	, new Person("张三", 19, 182)
	).collect(Collectors.groupingBy(p -> p.getAge() >= 18 ? "成年" : "未成
	年"));
map2.forEach((k,v)-> System.out.println("k=" + k +"\t"+ "v=" + v));

多级分组: 先根据name分组然后根据年龄分组

// 先根据name分组,然后根据age(成年和未成年)分组
Map<String,Map<Object,List<Person>>> map = Stream.of(
	new Person("张三", 18, 175)
	, new Person("李四", 22, 177)
	, new Person("张三", 14, 165)
	, new Person("李四", 15, 166)
	, new Person("张三", 19, 182)
	).collect(Collectors.groupingBy(Person::getName
	,Collectors.groupingBy(p->p.getAge()>=18?"成年":"未成年"
	)
	));
map.forEach((k,v)->{
	System.out.println(k);
	v.forEach((k1,v1)->{
	System.out.println("\t"+k1 + "=" + v1);
	});
	});
}
对流中的数据做分区操作

Collectors.partitioningBy会根据值是否为true,把集合中的数据分割为两个列表,一个true列表,一个false列表

Map<Boolean, List<Person>> map = Stream.of(
new Person("张三", 18, 175)
, new Person("李四", 22, 177)
, new Person("张三", 14, 165)
, new Person("李四", 15, 166)
, new Person("张三", 19, 182)
).collect(Collectors.partitioningBy(p -> p.getAge() > 18));
map.forEach((k,v)-> System.out.println(k+"\t" + v));

对流中的数据做拼接

Collectors.joining会根据指定的连接符,将所有的元素连接成一个字符串

并行流
/**
* 获取并行流的两种方式
*/

List<Integer> list = new ArrayList<>();
// 通过List 接口 直接获取并行流
Stream<Integer> integerStream = list.parallelStream();
// 将已有的串行流转换为并行流
Stream<Integer> parallel = Stream.of(1, 2, 3).parallel();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值