Lambda表达式简述 :
Lambda表达式是Java 8引入的一种函数式编程特性,它允许我们以更简洁和灵活的方式定义和传递匿名函数。Lambda表达式可以替代使用匿名内部类的场景,使代码更加简洁易读。
Lambda表达式可以用于函数式接口,即只包含一个抽象方法的接口。通过Lambda表达式,我们可以直接实现接口的抽象方法,并将Lambda表达式作为接口的实例进行传递、赋值或调用。
Lambda表达式的优势在于简洁性和可读性,可以减少冗余的代码,使代码更加紧凑和易于理解。它在函数式编程、集合操作、并行处理等方面提供了更便捷和灵活的编程方式。
个人练习实例:
package com.xcl.Test;
import com.xcl.pojo.Author;
import com.xcl.pojo.Book;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.System.*;
/**
* @author xcl
* @version 1.0x
* @date 2023/7/9 19:12
*/
public class Demo5 {
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors(); // list
// System.out.println(authors);
// 把集合转为流 打印年龄小于18的作家的名字
// String s1 = authors.stream().distinct().filter(s-> s.getAge()<18).collect(Collectors.toList()).toString();
// distinct 去重 filter 过滤判断 foreach 遍历输出 有终结操作才可以打印出来数据
// authors.stream()
// .distinct()
// .filter(author -> author.getAge() < 18)
// .forEach(author -> out.println(author.getName()));
// System.out.println(s1);
// Integer[] arr = {1,2,3,44,5,3}; // 数组
// Stream<Integer> stream = Arrays.stream(arr);
// stream.distinct().filter(Integer->Integer>2).forEach(out::println);
// HashMap<String, Integer> map = new HashMap<>(); // map
// map.put("zhang",19);
// map.put("li",19);
// map.put("wang",19);
// map.put("wang",19);
// Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
// stream.distinct().filter(stringIntegerEntry -> stringIntegerEntry.getKey().equals("wang")).forEach(stringIntegerEntry -> out.println(stringIntegerEntry));
// int sum =0;
// // 对数组求和
// int[] a = {1,2,3};
// for (int i : a) {
// sum += i;
// }
// out.println(sum);
// 打印所有姓名长度大于3的作家的名字
// authors.stream().filter(author -> author.getName().length() > 3).forEach(author -> out.println(author.getName()));
// test01();
// test02();
// test03();
// test04();
// test05();
test06();
// test07(); 以上为中间操作
// test08();
// test09();
// test10();
// test11();
// test12();
// test13();
// test14();
// test15();
// test16(); 查找匹配操作
// test17(); // 以下为reduce操作 归并操作 缩减操作
// test18(); // 以下为reduce操作 归并操作 缩减操作
// test19(); // 以下为reduce操作 归并操作 缩减操作
// test20(); // 以下为reduce操作 归并操作 缩减操作
// test21(); // Optional 避免臃肿的代码判断非空 来造成的空指针异常 获取到空数据 相当于是一个包装类
// ofNullable
// Author author = test22();// Optional
// Optional<Author> author1 = Optional.ofNullable(author); // 封装一个对象 判断是否为空
// author1.ifPresent(author2 -> out.println(author2.getName())); // 避免空指针异常
// Author author2 = test23();// Optional
// Optional<Author> author21 = Optional.ofNullable(author2);
// out.println(author21);
// String name = author2.getName();
// out.println(name);
// test24().ifPresent(author3 ->out.println(author3));// Optional
// Author author = test24().orElseGet(() -> new Author());
// test24().orElseThrow((Supplier<Throwable>) () -> new RuntimeException("空的对象"));
// out.println(author);
// test25();
// test26();
// test27(); // and
// test28();
// test29(); 上面的为串行流
// test30();
// test31();
// test32();
}
private static void test32() {
List<Author> authors = getAuthors();
List<List<Book>> collect = authors.stream().distinct().map(author -> author.getBooks()).collect(Collectors.toList());
Map<Object, List<Book>> collect1 = collect.stream().flatMap(Collection::stream).collect(Collectors.groupingBy(Book::getId));
out.println(collect);
out.println(collect1);
}
private static void test31() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 56, 4, 7,80,79,99,8888,80088,222,2222,22,222222222,2,2,222222,22222222,222222);
Integer integer = integerStream.parallel().peek(integer1 -> {
out.println(integer1 + "当前线程名称 =" + Thread.currentThread().getName());
}).filter((Integer integer12) -> {
return integer12 > 5;
}).reduce(Integer::sum).get();
out.println(integer);
}
private static void test30() { //parallel() 串行流可以通过parallel方法来转换为并行流操作
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 56, 4, 7,80,79,99,8888,80088);
Integer integer = integerStream.parallel().filter(integer1 -> {
return integer1 > 10;
}).reduce((a, b) -> {
return Integer.sum(a, b);
}).get();
out.println(integer);
}
private static void test29() {
List<Author> authors = getAuthors();
authors.stream().mapToInt(value -> value.getAge() + 10).filter(value -> value > 10).forEach(out::println);
}
private static void test28() {
List<Author> authors = getAuthors();
LocalDate firstDayOfYear = LocalDate.now().withDayOfYear(1);
LocalDateTime firstSecondOfYear = firstDayOfYear.atStartOfDay();
System.out.println("当前年的第一天: " + firstSecondOfYear);
authors.stream().distinct().filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 1 || author.getName().length() > 3;
}
}).forEach(new Consumer<Author>() {
@Override
public void accept(Author author) {
out.println(author);
}
});
}
private static void test27() {
List<Author> authors = getAuthors();
authors.stream().filter(author -> author.getAge() > 17 && author.getName().length() > 3).forEach(out::println);
}
private static void test26() {
Optional<Author> author = test24();
Optional<List<Book>> books = author.map(Author::getBooks);
books.ifPresent(out::println);
}
private static void test25() { //ifPresent 不为空就输出
Optional<Author> author = test24();
author.filter(author1 -> author1.getAge() > 18).ifPresent(out::println);
boolean present = author.filter(author1 -> author1.getAge() > 18).isPresent(); // isPresent 数据为不为空的判断
out.println(present);
}
private static Optional<Author> test24() {
Author author = new Author(1L, "zhangsan", 22, "一个有趣的人", null);
return Optional.of(author);
}
private static Author test23() {
return new Author();
}
private static Author test22() {
return new Author(1L, "zhangsan", 22, "一个有趣的人", null);
}
private static void test21() { //流是一次性的 执行完一次流之后不可以再次使用
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
stream.map(Author::getName).forEach(out::println); // 一次性操作
}
private static void test20() { //// 求年龄的最小值 reduce 实现 一个参数 内部参数计算
List<Author> authors = getAuthors();
Optional<Integer> reduce = authors.stream().distinct().map(Author::getAge).reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer integer, Integer integer2) {
return integer < integer2 ? integer : integer2;
}
});//ifPresent 如果有就返回 如果没有就返回空
reduce.ifPresent(out::println);
}
private static void test19() { // 求年龄的最小值 reduce 实现 两个参数 实现
List<Author> authors = getAuthors();
// Integer reduce = authors.stream().distinct().map(s -> s.getAge()).reduce(Integer.MAX_VALUE, (result, integer2) -> result < integer2 ? result : integer2);
Integer reduce = authors.stream().distinct().map(Author::getAge).reduce(Integer.MAX_VALUE, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer integer, Integer integer2) {
return integer < integer2 ? integer : integer2;
}
});
out.println(reduce);
}
private static void test18() { // 求年龄的最大值 reduce 实现 result是初始化的sum值 integer2是 累加值
List<Author> authors = getAuthors();
Integer reduce = authors.stream().distinct().map(Author::getAge).reduce(Integer.MIN_VALUE, (Integer result, Integer integer2) -> {
return result > integer2 ? result : integer2;
});
out.println(reduce);
}
private static void test17() { // 使用reduce 求出所有作者的和
List<Author> authors = getAuthors();
Integer s1 = authors.stream().distinct().map(Author::getAge).reduce(0, Integer::sum);
out.println(s1);
}
private static void test16() {
List<Author> authors = getAuthors();
authors.stream().distinct().min(Comparator.comparingInt(Author::getAge)).ifPresent(author -> out.println(author.getName()));
}
private static void test15() { // 获取任意一个年龄大于18 的作家 如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> any = authors.stream().distinct().filter(s -> s.getAge() > 18).findAny();
any.ifPresent(author -> out.println(author.getName()));
}
private static void test14() { // 判断所有的作家是否都没有超过100岁
List<Author> authors = getAuthors();
boolean b = authors.stream().allMatch(s -> s.getAge() < 100);
boolean b1 = authors.stream().noneMatch(s -> s.getAge() > 101);
out.println(b1);
}
private static void test13() { // 判断一下是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean b = authors.stream().allMatch(author -> author.getAge() > 17);
out.println(b);
}
private static void test12() { // 获取一个map集合
List<Author> authors = getAuthors();
Map<String, ArrayList<Book>> collect = authors.stream().distinct().collect(Collectors.toMap(Author::getName, author -> new ArrayList<>(author.getBooks())));
out.println(collect);
}
private static void test11() { // 判断是否有一个年龄在29岁以上的作家
List<Author> authors = getAuthors();
boolean b = authors.stream().distinct().anyMatch(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 29;
}
});
out.println(b);
}
private static void test10() { // 分别获取这些作家的所有书籍的最高和最低分打印
List<Author> authors = getAuthors();
Optional<Book> max = authors.stream().distinct().flatMap(author -> author.getBooks().stream()).distinct().max((o1, o2) -> o1.getScor() - o2.getScor());
Optional<Book> min = authors.stream().distinct().flatMap(author -> author.getBooks().stream()).distinct().min((o1, o2) -> o1.getScor() - o2.getScor());
out.println("最大的分数的名字:" + max.get().getName());
out.println("最小分数的名字:" + min.get().getName());
}
private static void test09() { // 去重所有书籍的个数
List<Author> authors = getAuthors();
long count = authors.stream().distinct().flatMap((Function<Author, Stream<?>>) author -> author.getBooks().stream()).distinct().count();
out.println(count);
}
private static void test08() {
}
private static void test07() { // map过滤操作
List<Author> authors = getAuthors();
List<Object> collect = authors.stream().map(new Function<Author, Object>() {
@Override
public Object apply(Author author) {
return author.getBooks();
}
}).collect(Collectors.toList());
out.println(collect);
}
private static void test06() { // 打印所有的书名分类并且去重以逗号分割
List<Author> authors = getAuthors();
List<String> collect = authors.stream().distinct().flatMap(author -> author.getBooks().stream()).distinct().flatMap(s -> Arrays.stream(s.getCategory().split(","))).distinct().collect(Collectors.toList());
out.println(collect);
}
private static void test05() { // 打印所有数据的名字 要求去重
List<Author> authors = getAuthors();
// List<Object> collect = authors.stream().map(new Function<Author, Object>() {
// @Override
// public Object apply(Author author) {
// return author.getBooks();
// }
// }).collect(Collectors.toList());
// List<Object> collect1 = collect.stream().distinct().collect(Collectors.toList());
// out.println(collect);
// out.println(collect1);
authors.stream().distinct().flatMap((Function<Author, Stream<Book>>) author -> author.getBooks().stream()).distinct().forEach(book -> out.println(book.getName()));
}
private static void test04() { // 打印跳过年龄最大的
List<Author> authors = getAuthors();
List<Author> collect = authors.stream().distinct().sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o1.getAge() - o2.getAge();
}
}).skip(1).collect(Collectors.toList());
out.println(collect);
}
private static void test03() {
List<Author> authors = getAuthors();
List<Author> collect = authors.stream().distinct().sorted((o1, o2) -> o2.getAge() - o1.getAge()).limit(3).collect(Collectors.toList());
out.println(collect);
}
private static void test02() {
List<Author> authors = getAuthors(); // list 根据年龄降序
List<Author> collect = authors.stream().distinct().sorted((o1, o2) -> o2.getAge() - o1.getAge()).collect(Collectors.toList());
out.println(collect);
}
private static void test01() {
// 打印所有作家的名字
List<Author> authors = getAuthors(); // list
// String s1 = authors.stream().map(Author::getName).collect(Collectors.toList()).toString();
authors.stream().map(s -> s.getName()).forEach(s -> out.println(s.trim()));
}
private static List<Author> getAuthors() {
// 初始化数据
Author author = new Author(1L, " 李四sa", 33, "祖安人", null);
Author author2 = new Author(3L, "赵四", 15, "祖人", null);
Author author3 = new Author(4L, "徐四", 14, "一祖安人", null);
Author author4 = new Author(4L, "徐四", 14, "一祖安人", null);
// 书籍列表
ArrayList<Book> books1 = new ArrayList<>();
ArrayList<Book> books2 = new ArrayList<>();
ArrayList<Book> books3 = new ArrayList<>();
books1.add(new Book(1L, "爱与恨", "哲学,纪录", 88, "爱与恨"));
books1.add(new Book(2L, "爱与恨的专辑", "哲学,小说", 99, "爱与恨的专辑"));
books2.add(new Book(3L, "春风", "哲学,个人专辑", 85, "激情澎湃"));
books2.add(new Book(3L, "春风", "哲学,个人专辑", 85, "激情澎湃"));
books2.add(new Book(4L, "春风十里", "哲学,爱情", 56, "春风十里"));
books3.add(new Book(5L, "风雨之上", "爱情", 56, "风和雨之上"));
books3.add(new Book(6L, "风与雨", "都市", 100, "两个人一个叫风一个叫雨"));
books3.add(new Book(6L, "风与雨", "都市", 100, "两个人一个叫风一个叫雨"));
author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);
ArrayList<Author> authors = new ArrayList<>(Arrays.asList(author, author2, author3, author4));
return authors;
}
}