java8实战

lambda表达式

java8中最重要的新特性,lambda表达式的使用场景:任何有函数式接口(有且仅有一个抽象方法,但是可以有多个非抽象方法的接口)的地方,Lambda把函数作为一个方法的参数,因此代码更加简洁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* lambda表达式
*/
private static void testLambda() throws Exception{
/**
* Runnable 类上有@FunctionalInterface作为函数式接口标示
* 无参数,无返回值
*/
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("lambda入门第一列");
}
};
r1.run();
Runnable r2 = () -> {System.out.println("lambda入门第一列包含大括号");};
r2.run();
Runnable r3 = () -> System.out.println("lambda入门第一列不包含大括号");
r3.run();

/**
* 无参数,有返回值
*/
Callable<String> c1 = new Callable<String>() {
@Override
public String call() throws Exception {
return "hello";
}
};

Callable<String> c2 = () -> {return "hello有括号";};
Callable<String> c3 = () -> "hello无括号";

System.out.println(c1.call());
System.out.println(c2.call());
System.out.println(c3.call());

/**
* 有参数有返回
* 输入一个字符串,返回输入字符串的大写
* aaa -> AAA
* Function 一个输入一个输出
*/
Function<String, String> fn = (str) -> str.toUpperCase();
System.out.println(fn.apply("admin"));

/**
* 有参数无返回
* Consumer 一个输入
*/
Consumer<String> c = arg -> {System.out.println(arg);};
c.accept("hello");


/**
* forEach(Consumer<? super T> action)
* 实际上集合的遍历,里面用的就是输入型function
*/
List<String> stringList = Arrays.asList("chenghao", "xiaode", "jiajia");
stringList.forEach(System.out::println);
}

方法引用

方法引用通过方法的名字来指向一个方法,使用冒号::表示引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @author chenghao
* @date 2019/9/7
*/
public class QuoteDemo {
/**
* 方法引用
*/
private static void testQuote(){
/**
* 静态方法引用
* 如果函数式接口的实现恰好是通过调用一个静态方法来实现,那么就可以使用静态方法引用
* 类名::staticMethod
*/
Supplier supplier1 = () -> Person.study();
System.out.println(supplier1.get());
Supplier supplier2 = Person::study;
System.out.println(supplier2.get());

/**
*实例方法引用
*如果函数式接口的实现恰好可以通过调用一个实例的实例方法来实现,那么就可以使用实例方法引用
*/
Function<String,String> function1 = str -> new Change().change(str);
System.out.println(function1.apply("test1"));
Function<String,String> function2 = new Change()::change;
System.out.println(function2.apply("test2"));

/**
* 构造器引用
* 比如在jpa中findById查找后,返回Optional,调用orElseThrow(自定义异常::new)
*/
Supplier<Person> s1 = () -> new Person();
s1.get();
Supplier<Person> s2 = Person::new;
s2.get();
}

public static void main(String[] args) {
testQuote();
}
}


class Person {
public Person(){
System.out.println("构造器");
}
public static String study() {
return "1";
}
}


class Change{
public String change(String str){
return str.toUpperCase();
}
}

stream

stream是用来处理数组和集合的API,Stream分为源source,多个中间操作,一个终止操作

  1. 源source可以是数组,集合,Stream.generate,Stream.iterate或者其它API进行创建
  2. 中间操作可以是零个或者多个,每一个中间操作会生成新的流。
  3. 流只有在遇到终止操作,它的流才开始遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class StreamDemo {
public static void createStream(){
/**
* 利用数组创建stream
*/
String[] arr ={"1","2"};
Stream<String> stream1 = Stream.of(arr);
stream1.forEach(System.out::println);
/**
* 利用集合创建stream
*/
List<String> stringList = Arrays.asList("3", "4");
Stream<String> stream2 = stringList.stream();
stream2.forEach(System.out::println);
/**
* filter
*/
Arrays.asList(1,2,3,4,5).stream()
.filter(x -> x%2==0).forEach(System.out::println);
/**
* distinct
*/
Arrays.asList(1,2,3,3,2).stream()
.distinct().forEach(System.out::println);
/**
* sorted
*/
Arrays.asList(9,7,8,6).stream()
.sorted().forEach(System.out::println);
/**
* map
*/
Arrays.asList("13","12").stream()
.map(Integer::valueOf).forEach(System.out::println);
/**
* mapToInt sum
*/
int sum = Arrays.asList(16, 17).stream()
.mapToInt(x -> x).sum();
System.out.println(sum);
/**
* limit
*/
Arrays.asList(20,23,99,88).stream()
.limit(3).forEach(System.out::println);
/**
* max,min
*/
Integer integer = Arrays.asList(10, 14, 12).stream()
.max((a, b) -> a - b).get();
System.out.println(integer);
/**
* 从1-50里面的所有偶数找出来你,放到一个list里面
*/
List<Integer> list = Stream.iterate(1, x -> x + 1).limit(50)
.filter(x -> x%2 == 0).collect(Collectors.toList());
System.out.println(list);
}

public static void main(String[] args) {
createStream();
}
}

综合应用实战篇

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @author chenghao
* @date 2019/9/7
*/
public class LambdaStreamDemo {
private static void test(){
/**
* 实战1 获取url后面的参数
* index.action?username=chenghao&userId=1&type=20&token=adfded&age=18
*/
String str="username=chenghao&userId=1&type=20&token=adfded&age=18";
Map<String, String> urlMap = Stream.of(str.split("&"))
.map(x -> x.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
System.out.println(urlMap);
/**
* 实战2 只将集合中id返回给前端
*/
List<Book> books = Book.books();
List<Integer> collect = books.stream()
.map(Book::getId).collect(Collectors.toList());
System.out.println(collect);
/**
* 实战3 将书的类型去重后返回给前端
*/
List<String> collect1 = Book.books().stream()
.map(Book::getType).distinct().collect(Collectors.toList());
System.out.println(collect1);

Set<String> collect2 = Book.books().stream()
.map(Book::getType).collect(Collectors.toSet());
System.out.println(collect2);
/**
* 实战4 将书的价格大于60,按发版日期降序传给前端
*/
Book.books().stream().filter(book -> book.getPrice()>60)
.sorted(Comparator.comparing(Book::getPublishDate).reversed())
.forEach(System.out::print);
/**
* 实战5 转map 将book 转换为对应id 的map
*/
Map<Integer, Book> map = Book.books().stream()
.collect(Collectors.toMap(Book::getId, book -> book));
System.out.println(map);
/**
* 实战6 最大小 将book最贵的返回给前端
*/
Optional<Book> collect3 = Book.books().stream()
.collect(Collectors.maxBy(Comparator.comparing(Book::getPrice)));
System.out.println(collect3);
/**
* 实战7 按类型分组后,取每组价格最高端
*/
Map<String, Optional<Book>> collect4 = Book.books().stream()
.collect(Collectors.groupingBy(Book::getType,
Collectors.maxBy(Comparator.comparing(Book::getPrice))));
System.out.println(collect4);
}
public static void main(String[] args) {
test();
}
}