1、什么是 Lambda 表达式
public class T01_Lambda {@Testpublic void test01() {// 匿名内部类Runnable runnable = new Runnable() {@Overridepublic void run() {System.out.println("开启新的线程 ...");}};Thread thread = new Thread(runnable);thread.start();}public void test02() {// Lambda 表达式Runnable runnable = () -> System.out.println("开启新的线程 ...");Thread thread = new Thread(runnable);thread.start();}
}
2、Lambda 表达式语法
(参数列表) -> { 代码/表达式 }
public class T03_LambdaSyntax {public static void main(String[] args) {// 1、无参无返回值Print01 p1 = () -> System.out.println("你好");p1.print();// 2、单个参数无返回值Print02 p2 = s -> System.out.println(s);p2.print("你好");// 3、多个参数无返回值Math01 m1 = (x, y) -> System.out.println(x * y);m1.operation(10, 15);// 4、多个参数有返回值Math02 m2 = (x, y) -> x * y;System.out.println(m2.operation(10, 15));}public interface Print01 {// 1、无参无返回值void print();}public interface Print02 {//2、单个参数无返回值void print(String s);}public interface Math01 {// 3、多个参数无返回值void operation(int x, int y);}public interface Math02 {// 4、多个参数有返回值int operation(int x, int y);}
}
public class T03_LambdaForeach {// 方式一:使用 foreach() 方法遍历集合,使用 return 终止遍历。后续代码继续执行,**相当于 continue**。@Testpublic void test01() {List<String> list = Arrays.asList("A", "B", "C");list.forEach(s -> {if ("B".equals(s)) {System.out.print(" 终止或跳出循环 ");
// continue;
// break;return;}System.out.print(s);});// 结果:A 终止或跳出循环 C}// 方式二:使用 foreach() 方法遍历集合,使用 throw 抛出异常但不处理。后续代码没有执行,**相当于 break**。@Testpublic void test02() {List<String> list = Arrays.asList("A", "B", "C");try {list.forEach(s -> {if ("B".equals(s)) {System.out.print(" 终止或跳出循环 ");throw new RuntimeException(" 终止或跳出循环 ");}System.out.print(s);});} catch (RuntimeException e) {}// 结果:A 终止或跳出循环}// 方式三:使用增强 for 循环遍历集合,**使用 continue、break 终止遍历**。@Testpublic void test03() {List<String> list = Arrays.asList("A", "B", "C");for (String s : list) {if ("B".equals(s)) {System.out.print(" 终止或跳出循环 ");
// continue;break;}System.out.print(s);}// continue 结果:A 终止或跳出循环 C// break 结果:A 终止或跳出循环}
}
// 方法引用
public class T01_MethodReference {// 调用实例方法:实例::实例方法名@Testpublic void test01() {Consumer<String> consumer1 = s -> System.out.println(s);consumer1.accept("张三");// 以上 Lambda 表达式,存在已有实现(out 实例的方法),因此可替换为方法引用Consumer<String> consumer2 = System.out::println;consumer2.accept("张三");}// 调用实例方法:类名::实例方法名@Testpublic void test02() {Function<String, Integer> function1 = s -> s.length();System.out.println(function1.apply("张三"));// 以上 Lambda 表达式,存在已有实现(String 类的实例方法),因此可替换为方法引用Function<String, Integer> function2 = String::length;System.out.println(function2.apply("张三"));}// 调用静态方法:类名::静态方法名@Testpublic void test03() {Function<Integer, String> function1 = integer -> String.valueOf(integer);System.out.println(function1.apply(30));// 以上 Lambda 表达式,存在已有实现(String 类的静态方法),因此可替换为方法引用Function<Integer, String> function2 = String::valueOf;System.out.println(function2.apply(30));}// 调用构造方法:类名::new@Testpublic void test04() {Supplier<Object> supplier1 = () -> new Object();System.out.());// 以上 Lambda 表达式,存在已有实现(Object 类的构造方法),因此可替换为方法引用Supplier<Object> supplier2 = Object::new;System.out.());}// 调用数组构造方法:类名[]::new@Testpublic void test05() {Function<Integer, String[]> function1 = integer -> new String[integer];System.out.String(function1.apply(10)));// 以上 Lambda 表达式,存在已有实现(String 数组的构造方法),因此可替换为方法引用Function<Integer, String[]> function2 = String[]::new;System.out.String(function2.apply(10)));}
}
1、什么是函数式接口
2、@FunctionalInterface 注解
// 自定义函数式接口
@FunctionalInterface
public interface T01_FunctionalInterface {void print();default void print(Integer i) {System.out.println(i);}static void print(String s) {System.out.println(s);}String toString();
}
3、四大核心函数式接口
public class T02_FunctionalInterface {public static void main(String[] args) {Consumer<Integer> consumer = x -> x = x + 10;Supplier<Integer> supplier = () -> 5 * 5;Function<Integer, Integer> function = x -> x * x;Predicate<Integer> predicate = x -> x > 10;}
}
1、Consumer 接口
package java.util.function;@FunctionalInterface
public interface Consumer<T> {void accept(T t);default Consumer<T> andThen(Consumer<? super T> after) {quireNonNull(after);return (T t) -> { accept(t); after.accept(t); };}
}
2、示例
// 指定字符串,先输出其长度,再输出其大写,再输出其小写
public class T01_Consumer {@Testpublic void test01() {print("Java", s -> System.out.println(s.length()), s -> System.out.UpperCase()), s -> System.out.LowerCase()));}public void print(String s, Consumer<String> c1, Consumer<String> c2, Consumer<String> c3) {// 组合多个函数Consumer<String> consumer = c1.andThen(c2).andThen(c3);// 执行函数consumer.accept(s);}
}
1、Supplier 接口
package java.util.function;@FunctionalInterface
public interface Supplier<T> {T get();
}
2、示例
// 产生 10 个 0~100 之间的整数,添加到集合中
public class T01_Supplier {@Testpublic void test01() {List<Integer> list = getList(10, () -> (new Random().nextInt(100)));list.forEach(System.out::println);}public List<Integer> getList(int length, Supplier<Integer> supplier) {List<Integer> list = new ArrayList<>();for (int i = 0; i < length; i++) {// 执行函数Integer integer = ();// 每次执行获得一个结果list.add(integer);}return list;}
}
1、Function 接口
package java.util.function;@FunctionalInterface
public interface Function<T, R> {R apply(T t);default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {quireNonNull(before);return (V v) -> apply(before.apply(v));}default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {quireNonNull(after);return (T t) -> after.apply(apply(t));}static <T> Function<T, T> identity() {return t -> t;}
}
2、示例
// 输入“张三,30”,先截取年龄,再转为数字,再给年龄加 1
public class T01_Function {@Testpublic void test01() {Integer calc = calc("张三,30", s -> s.trim().split(",")[1], s -> Integer.parseInt(s), s -> s + 1);System.out.println(calc);}public Integer calc(String s, Function<String, String> f1, Function<String, Integer> f2, Function<Integer, Integer> f3) {// 返回组合函数。将前一个函数的结果,作为后一个函数的参数Function<String, Integer> function = f3pose(f2pose(f1));// 先将 f1 的结果作为 f2 的参数,再将 f2 的结果作为 f3 的参数return function.apply(s);}
}
1、Predicate 接口
package java.util.function;@FunctionalInterface
public interface Predicate<T> {boolean test(T t);default Predicate<T> and(Predicate<? super T> other) {quireNonNull(other);return (t) -> test(t) && st(t);}default Predicate<T> negate() {return (t) -> !test(t);}default Predicate<T> or(Predicate<? super T> other) {quireNonNull(other);return (t) -> test(t) || st(t);}static <T> Predicate<T> isEqual(Object targetRef) {return (null == targetRef)? Objects::isNull: object -> targetRef.equals(object);}
}
2、Predicate 接口示例
@Testpublic void test01() {isTrue("ABC", s -> s.startsWith("A"), s -> s.length() == 2);}public void isTrue(String s, Predicate<String> p1, Predicate<String> p2) {System.out.println("是否以 A 开始:" + p1.test(s));System.out.println("是否非 A 开始:" + p1.negate().test(s));System.out.println("是否以 A 开始,而且长度为 3:" + p1.and(p2).test(s));System.out.println("是否以 A 开始,或者长度为 3:" + p1.or(p2).test(s));System.out.println("输入参数是否等于 ABC:" + Predicate.isEqual("ABC").test(s));}
}
1、什么是 Stream 流
2、如何获取 Stream 流
public class T01_GetStream {@Testpublic void test01() {String[] s = new String[]{"张三", "李四", "王五"};Arrays.stream(s).forEach(System.out::println);// 张三 李四 王五Stream.of(s).forEach(System.out::println);// 张三 李四 王五}@Testpublic void test02() {Collection<String> collection = Arrays.asList("张三", "李四", "王五");collection.stream().forEach(System.out::println);// 张三 李四 王五}@Testpublic void test03() {Map<String, String> map = new HashMap<>();map.put("张三", "zhangsan");map.put("李四", "lisi");map.put("王五", "wangwu");map.keySet().stream().forEach(System.out::print);// 李四 张三 王五map.values().stream().forEach(System.out::println);// lisi Set().stream().forEach(System.out::println);// 李四=lisi 张三=zhangsan 王五=wangwu}
}
package java.util.stream;
public interface BaseStream<T, S extends BaseStream<T, S>> extends AutoCloseable {Iterator<T> iterator();Spliterator<T> spliterator();boolean isParallel();S sequential();S parallel();S unordered();S onClose(Runnable closeHandler);@Overridevoid close();
}
package java.util;
public final class Optional<T> {private static final Optional<?> EMPTY = new Optional<>();private final T value;private Optional() {this.value = null;}public static<T> Optional<T> empty() {}public static <T> Optional<T> of(T value) {}public static <T> Optional<T> ofNullable(T value) {}public T get() {}// 获取public boolean isPresent() {}// 判断是否存在public void ifPresent(Consumer<? super T> consumer) {}// 如果存在,执行消费函数public Optional<T> filter(Predicate<? super T> predicate) {}// 过滤,根据断定函数public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {}// 映射,根据函数public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {}// 映射,根据函数public T orElse(T other) {}// 如果存在,返回该值,否则返回 T otherpublic T orElseGet(Supplier<? extends T> other) {}// 如果存在,返回该值,否则返回供给型函数生成的结果public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {}// 如果存在,返回该值,否则抛出供给函数生成的异常
}
package java.util.stream;
public interface Stream<T> extends BaseStream<T, Stream<T>> {// 1、遍历void forEach(Consumer<? super T> action);// 遍历void forEachOrdered(Consumer<? super T> action);// 顺序遍历// 2、排序Stream<T> sorted();// 自然排序Stream<T> sorted(Comparator<? super T> comparator);// 比较器排序// 3、过滤Stream<T> filter(Predicate<? super T> predicate);// 4、映射<R> Stream<R> map(Function<? super T, ? extends R> mapper);IntStream mapToInt(ToIntFunction<? super T> mapper);LongStream mapToLong(ToLongFunction<? super T> mapper);DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);// 5、归纳Optional<T> reduce(BinaryOperator<T> accumulator);// 不能改变归纳类型,无初始值T reduce(T identity, BinaryOperator<T> accumulator);// 不能改变归纳类型,有初始值<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);// 可以改变归纳类型,有初始值// 6、窥视Stream<T> peek(Consumer<? super T> action);// 7.1、最小、最大、计数、匹配、查找Optional<T> min(Comparator<? super T> comparator);// 最小Optional<T> max(Comparator<? super T> comparator);// 最大long count();// 计数boolean anyMatch(Predicate<? super T> predicate);// 匹配(任意一个符合条件则返回 true)boolean allMatch(Predicate<? super T> predicate);// 匹配(全部元素符合条件则返回 true)boolean noneMatch(Predicate<? super T> predicate);// 匹配(没有一个符合条件则返回 true)Optional<T> findFirst();// 查找Optional<T> findAny();// 查找// 7.2、去重、限量、跳过Stream<T> distinct();Stream<T> limit(long maxSize);// 限量Stream<T> skip(long n);// 跳过// 8、静态方法public static<T> Builder<T> builder() {}// 返回流构建器,用于构建流public static<T> Stream<T> empty() {}// 返回空流,然后使用 concat() 合并流public static<T> Stream<T> of(T t) {}// 转换为流public static<T> Stream<T> values) {}// 转换为流public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {}// 生成无限流,根据指定种子public static<T> Stream<T> generate(Supplier<T> s) {}// 生成无限流public static<T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {}// 合并流public interface Builder<T> extends Consumer<T> {@Overridevoid accept(T t);default Builder<T> add(T t) {}Stream<T> build();}// 9.1、转换为数组Object[] toArray();// 收集为 Object 类型的数组<A> A[] toArray(IntFunction<A[]> generator);// 收集为指定类型的数组// 9.2、收集为集合<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);// 自定义收集<R, A> R collect(Collector<? super T, A, R> collector);// 指定收集器收集
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {private String name;private String gender;private Integer age;private String address;private Double salary;public static List<Employee> getList() {List<Employee> list = new ArrayList<>();list.add(new Employee("张三", "男", 17, "西安", 6500.0D));list.add(new Employee("李四", "女", 19, "郑州", 4000.0D));list.add(new Employee("王五", "男", 18, "上海", 4800.0D));list.add(new Employee("赵六", "女", 20, "北京", 4000.0D));list.add(new Employee("钱七", "男", 22, "武汉", 4500.0D));list.add(new Employee("孙八", "女", 21, "南京", 8000.0D));return list;}
}
/*// 1、遍历void forEach(Consumer<? super T> action);// 遍历void forEachOrdered(Consumer<? super T> action);// 顺序遍历*/
public class T01_Foreach {@Testpublic void test01() {List<String> list = Arrays.asList("B", "C", "A");list.stream().forEach(System.out::println);list.stream().forEachOrdered(System.out::println);}
}
1、如何获取并行流
// 如何获取并行流
public class T01_GetParallelStream {@Testpublic void test01() {List<String> list = new ArrayList<>();// 方式一:将串行流转换为并行流Stream<String> s1 = list.stream().parallel();// 方式二:直接生成并行流Stream<String> s2 = list.parallelStream();}
}
2、串行流与并行流的区别
// 串行流与并行流的区别
public class T02_ParallelStream {// 遍历区别@Testpublic void test01() {List<String> list = Arrays.asList("B", "C", "A");System.out.println("并行流 forEach() 方法");list.parallelStream().forEach(System.out::println);System.out.println("并行流 forEachOrdered() 方法");list.parallelStream().forEachOrdered(System.out::println);// 结果始终为:B C A}// 查找区别@Testpublic void test02() {List<String> list = Arrays.asList("B", "C", "A");Optional<String> any = list.parallelStream().findAny();System.out.());Optional<String> first = list.parallelStream().findFirst();System.out.());// 结果始终为:B}
}
/*// 2、排序Stream<T> sorted();// 自然排序Stream<T> sorted(Comparator<? super T> comparator);// 比较器排序*/
public class T01_Sorted {// 自然排序@Testpublic void test01() {List<String> list = Arrays.asList("B", "C", "A");list.stream().sorted().forEach(System.out::println);}// 比较器排序@Testpublic void test02() {List<Employee> employees = List();employees.stream().sorted((e1, e2) -> {double d = e2.getSalary() - e1.getSalary();int i = e1.getAge() - e2.getAge();return d > 0 ? 1 : (d < 0 ? -1 : i > 0 ? 1 : (i < 0 ? -1 : 0));}).forEach(System.out::println);}
}
/*// 3、过滤Stream<T> filter(Predicate<? super T> predicate);*/
public class T01_Filter {@Testpublic void test01() {List<String> list = Arrays.asList("乔峰", "段誉", "虚竹", "鸠摩智", "段正淳", "段延庆", "庄聚贤", "慕容复");// 以下写法结果相同list.stream().filter(s -> s.startsWith("段")).filter(s -> s.length() == 2).forEach(System.out::println);list.stream().filter(s -> s.startsWith("段") && s.length() == 2).forEach(System.out::println);}@Testpublic void test02() {List<Employee> list = List();// 以下写法结果相同list.stream().filter(e -> "男".Gender())).filter(e -> e.getSalary() >= 5000.0D).forEach(System.out::println);list.stream().filter(e -> "男".Gender()) && e.getSalary() >= 5000.0D).forEach(System.out::println);}
}
1、映射分类
2、示例一
/*// 4、映射<R> Stream<R> map(Function<? super T, ? extends R> mapper);IntStream mapToInt(ToIntFunction<? super T> mapper);LongStream mapToLong(ToLongFunction<? super T> mapper);DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);*/
public class T01_Map01 {// map()@Testpublic void test01() {List<Employee> list = List();Stream<String> stream1 = list.stream().map(Employee::getName);stream1.forEach(System.out::println);// 结果:张三 李四 王五 赵六 钱七 孙八}// flatMap()@Testpublic void test02() {List<Employee> list = List();Stream<String> stream2 = list.stream().flatMap(e -> Stream.Name().split("")));stream2.forEach(System.out::println);// 结果:张 三 李 四 王 五 赵 六 钱 七 孙 八}// map() 与 mapToInt() 的区别@Testpublic void test03() {List<Employee> list = List();Stream<Integer> stream = list.stream().map(Employee::getAge);IntStream intStream = list.stream().mapToInt(Employee::getAge);}// flatMap() 与 flatMapToInt() 的区别@Testpublic void test04() {List<Employee> list = List();Stream<Integer> stream = list.stream().flatMap(e -> Stream.Age(), e.getSalary().intValue()));IntStream intStream = list.stream().flatMapToInt(e -> IntStream.Age(), e.getSalary().intValue()));}
}
3、示例二
/*// 4、映射<R> Stream<R> map(Function<? super T, ? extends R> mapper);IntStream mapToInt(ToIntFunction<? super T> mapper);LongStream mapToLong(ToLongFunction<? super T> mapper);DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);*/
public class T01_Map02 {// 1、所有员工工资加 1000@Testpublic void test01() {List<Employee> list = List();Stream<Employee> stream = list.stream().map(e -> {Employee employee = new Employee();employee.Name());employee.Salary() + 1000.0D);return employee;});stream.forEach(System.out::println);}// 2、所有员工工资加 1000@Testpublic void test02() {List<Employee> list = List();Stream<Employee> stream = list.stream().map(e -> {e.Salary() + 1000.0D);return e;});stream.forEach(System.out::println);}
}
/*// 5、归纳Optional<T> reduce(BinaryOperator<T> accumulator);// 不能改变归纳类型,无初始值T reduce(T identity, BinaryOperator<T> accumulator);// 不能改变归纳类型,有初始值<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);// 可以改变归纳类型,有初始值*/
public class T01_Reduce {// 员工年龄求和@Testpublic void test01() {List<Employee> list = List();Optional<Integer> reduce = list.stream().map(Employee::getAge).reduce(Integer::sum);System.out.());}// 员工年龄求和@Testpublic void test02() {List<Employee> list = List();Integer reduce = list.stream().map(Employee::getAge).reduce(0, Integer::sum);System.out.println(reduce);}// 员工年龄求和@Testpublic void test03() {List<Employee> list = List();Integer reduce = list.stream().reduce(0, (age, e) -> Integer.sum(age, e.getAge()), Integer::sum);System.out.println(reduce);}
}
/*// 6、窥视Stream<T> peek(Consumer<? super T> action);peek()、map()、forEach() 的区别peek():进行消费型操作,返回操作之前的流。额外操作,不会改变流中的数据,但是可以改变流中数据的引用。map():进行函数型操作,返回操作之后的流。forEach():进行消费型操作,无返回值。peek()、map()、forEach() 方法Stream<T> peek(Consumer<? super T> action);<R> Stream<R> map(Function<? super T, ? extends R> mapper);void forEach(Consumer<? super T> action);*/
public class T01_Peek {// peek() 不会改变流中的数据@Testpublic void test01() {List<String> list = Arrays.asList("B", "C", "A");list.stream().peek(s -> System.out.println("额外操作:" + s.toLowerCase())).forEach(s -> System.out.println("遍历输出:" + s));}// peek() 但是可以改变流中数据的引用@Testpublic void test02() {List<Employee> list = List();list.stream().peek(e -> e.setAge(100)).forEach(System.out::println);}
}
/*// 7.1、最小、最大、计数、匹配、查找Optional<T> min(Comparator<? super T> comparator);// 最小Optional<T> max(Comparator<? super T> comparator);// 最大long count();// 计数boolean anyMatch(Predicate<? super T> predicate);// 匹配(任意一个符合条件则返回 true)boolean allMatch(Predicate<? super T> predicate);// 匹配(全部元素符合条件则返回 true)boolean noneMatch(Predicate<? super T> predicate);// 匹配(没有一个符合条件则返回 true)Optional<T> findFirst();// 查找Optional<T> findAny();// 查找// 7.2、去重、限量、跳过Stream<T> distinct();Stream<T> limit(long maxSize);// 限量Stream<T> skip(long n);// 跳过*/
public class T01_OtherMethods {@Testpublic void test01() {List<Employee> list = List();// 最小Optional<Employee> min = list.stream().min((o1, o2) -> o1.getAge() - o2.getAge());min.ifPresent(System.out::println);// 最大Optional<Employee> max = list.stream().max((o1, o2) -> o1.getAge() - o2.getAge());max.ifPresent(System.out::println);// 计数System.out.println(list.stream().count());// 匹配boolean b1 = list.stream().anyMatch(employee -> Age() > 20);boolean b2 = list.stream().allMatch(employee -> Age() > 20);boolean b3 = list.stream().noneMatch(employee -> Age() > 20);System.out.println(b1);System.out.println(b2);System.out.println(b3);// 查找Optional<Employee> first = list.stream().findFirst();Optional<Employee> any = list.stream().findAny();first.ifPresent(System.out::println);any.ifPresent(System.out::println);}@Testpublic void test02() {List<String> list = Arrays.asList("A", "B", "C", "A", "B", "C");// 去重System.out.println("去重:");list.stream().distinct().forEach(System.out::println);// A B CSystem.out.println("跳过、限量:");// 跳过、限量list.stream().skip(2).limit(2).forEach(System.out::println);// C A}
}
/*// 8、静态方法public static<T> Builder<T> builder() {}// 返回流构建器,用于构建流public static<T> Stream<T> empty() {}// 返回空流,然后使用 concat() 合并流public static<T> Stream<T> of(T t) {}// 转换为流public static<T> Stream<T> values) {}// 转换为流public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {}// 生成无限流,根据指定种子public static<T> Stream<T> generate(Supplier<T> s) {}// 生成无限流public static<T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {}// 合并流*/
public class T01_StaticMethods {// 1、转换为流@Testpublic void test01() {Stream<String> s1 = Stream.of("张三");Stream<String> s2 = Stream.of("张三", "李四", "王五");String[] array = new String[]{"张三", "李四", "王五"};Stream<String> s3 = Stream.of(array);}/*2、iterate() 生成无限流:1、生成字符串:张三-1 张三-2 张三-3 张三-4 张三-52、计算 5 的阶乘*/@Testpublic void test02() {Stream<String> stream = Stream.iterate("张三-1", s -> {String[] split = s.split("-");return split[0] + "-" + (Integer.parseInt(split[1]) + 1);}).limit(5);stream.forEach(System.out::println);Optional<Integer> optional = Stream.iterate(1, integer -> integer + 1).limit(5).reduce((i1, i2) -> i1 * i2);System.out.());}// 3、generate() 生成无限流:生成 10 个 100 以内的随机数@Testpublic void test03() {Stream<Integer> stream = ate(() -> new Random().nextInt(100)).limit(10);stream.forEach(System.out::println);}// 4、流构件器@Testpublic void test04() {Stream.Builder<String> builder = Stream.builder();Stream<String> stream = builder.add("张三").add("李四").add("王五").build();stream.forEach(System.out::println);}// 5、合并流@Testpublic void test05() {Stream<String> empty = pty();Stream<String> stream1 = Stream.of("张三", "李四", "王五");Stream<String> stream2 = at(empty, stream1);stream2.forEach(System.out::println);}
}
1、介绍
// 9.1、转换为数组
Object[] toArray();// 收集为 Object 类型的数组
<A> A[] toArray(IntFunction<A[]> generator);// 收集为指定类型的数组
// 9.2、收集为集合
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);// 自定义收集
<R, A> R collect(Collector<? super T, A, R> collector);// 指定收集器收集
package java.util.stream;
public final class Collectors {// 1.1、收集为指定 Collection、List、Setpublic static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {}// 收集为指定 Collectionpublic static <T> Collector<T, ?, List<T>> toList() {}// 收集为 Listpublic static <T> Collector<T, ?, Set<T>> toSet() {}// 收集为 Set// 1.2、收集为 Mappublic static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper) {}public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,BinaryOperator<U> mergeFunction) {}public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,BinaryOperator<U> mergeFunction,Supplier<M> mapSupplier) {}// 1.3、收集为 ConcurrentMappublic static <T, K, U> Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper) {}public static <T, K, U> Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,BinaryOperator<U> mergeFunction) {}public static <T, K, U, M extends ConcurrentMap<K, U>> Collector<T, ?, M> toConcurrentMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,BinaryOperator<U> mergeFunction,Supplier<M> mapSupplier) {}// 2、字符串连接public static Collector<CharSequence, ?, String> joining() {}public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) {}public static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) {}// 7、映射public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {}// 8、收集,然后执行 Functionpublic static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) {}// 3、统计:计数、最小、最大、求和、平均、统计所有public static <T> Collector<T, ?, Long> counting() {}// 计数public static <T> Collector<T, ?, Optional<T>> minBy(Comparator<? super T> comparator) {}// 最小public static <T> Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator) {}// 最大public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper) {}// 求和public static <T> Collector<T, ?, Long> summingLong(ToLongFunction<? super T> mapper) {}// 求和public static <T> Collector<T, ?, Double> summingDouble(ToDoubleFunction<? super T> mapper) {}// 求和public static <T> Collector<T, ?, Double> averagingInt(ToIntFunction<? super T> mapper) {}// 平均public static <T> Collector<T, ?, Double> averagingLong(ToLongFunction<? super T> mapper) {}// 平均public static <T> Collector<T, ?, Double> averagingDouble(ToDoubleFunction<? super T> mapper) {}// 平均public static <T> Collector<T, ?, IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper) {}// 统计所有public static <T> Collector<T, ?, LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper) {}// 统计所有public static <T> Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper) {}// 统计所有// 4、归纳public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op) {}public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op) {}public static <T, U> Collector<T, ?, U> reducing(U identity, Function<? super T, ? extends U> mapper, BinaryOperator<U> op) {}// 5.1、分组:返回 Mappublic static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T,? extends K> classifier) {}public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream) {}public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,Supplier<M> mapFactory,Collector<? super T, A, D> downstream) {}// 5.2、分组:返回 ConcurrentMappublic static <T, K> Collector<T, ?, ConcurrentMap<K, List<T>>> groupingByConcurrent(Function<? super T, ? extends K> classifier) {}public static <T, K, A, D>Collector<T, ?, ConcurrentMap<K, D>> groupingByConcurrent(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream) {}public static <T, K, A, D, M extends ConcurrentMap<K, D>> Collector<T, ?, M> groupingByConcurrent(Function<? super T, ? extends K> classifier,Supplier<M> mapFactory,Collector<? super T, A, D> downstream) {}// 6、分区public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {}public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,Collector<? super T, A, D> downstream) {}
}
2、收集为数组
/*// 9.1、转换为数组Object[] toArray();// 收集为 Object 类型的数组<A> A[] toArray(IntFunction<A[]> generator);// 收集为指定类型的数组*/
public class T01_ToArray {@Testpublic void test01() {List<Employee> list = List();Object[] objects = list.stream().toArray();for (Object object : objects) {System.out.println(object);}}@Testpublic void test02() {List<Employee> list = List();
// Employee[] employees = list.stream().toArray(i -> new Employee[i]);Employee[] employees = list.stream().toArray(Employee[]::new);for (Employee employee : employees) {System.out.Name());}}
}
3、收集为集合 - 自定义收集
/*// 9.2、收集为集合<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);// 自定义收集Supplier<R> supplier:提供一个收集数据的容器,容器的泛型为 R。例如 ArrayList<String>、HashMap<String, Employee>。BiConsumer<R, ? super T> accumulator:如何给容器添加数据,添加什么数据,容器的泛型为 R,流的泛型为 T。BiConsumer<R, R> combiner:如何将多个容器合并,容器的泛型为 R。*/
public class T02_Collect01 {@Testpublic void test01() {List<Employee> list = List();ArrayList<String> arrayList = list.stream().collect(ArrayList::new,(nameArrayList, e) -> nameArrayList.Name()),ArrayList::addAll);arrayList.forEach(System.out::println);}@Testpublic void test02() {List<Employee> list = List();HashMap<String, Employee> hashMap = list.stream().collect(HashMap::new,(nameHashMap, e) -> nameHashMap.Name(), e),HashMap::putAll);hashMap.forEach((k, v) -> System.out.println(k + "::" + v));}
}
4、收集为集合 - 指定收集器收集
package T19_Stream.T14_Collect;import T19_Stream.Employee;
import org.junit.Test;import java.util.*;
import java.util.stream.Collectors;/*Stream 接口<R, A> R collect(Collector<? super T, A, R> collector);// 指定收集器收集Collectors 类 - 收集器工具类*/
public class T03_Collect02 {// 1.1、收集为指定 Collection、List、Set@Testpublic void test01() {List<Employee> employees = List();ArrayList<Employee> arrayList = employees.stream().Collection(ArrayList::new));List<Employee> list = employees.stream().List());Set<Employee> set = employees.stream().Set());}// 1.2、收集为 Map@Testpublic void test02() {List<Employee> employees = List();Map<String, Integer> map1 = employees.stream().Map(Employee::getName, Employee::getAge));System.out.println(map1);Map<Integer, String> map2 = employees.stream().Map(Employee::getAge, Employee::getName, (o1, o2) -> o1));System.out.println(map2);HashMap<Integer, String> map3 = employees.stream().Map(Employee::getAge, Employee::getName, (o1, o2) -> o1, HashMap::new));System.out.println(map3);}// 2、字符串连接@Testpublic void test03() {List<Employee> employees = List();String s1 = employees.stream().map(Employee::getName).collect(Collectors.joining());System.out.println(s1);String s2 = employees.stream().map(Employee::getName).collect(Collectors.joining("-"));System.out.println(s2);String s3 = employees.stream().map(Employee::getName).collect(Collectors.joining("-", "开始<", ">结束"));System.out.println(s3);}// 3、统计:计数、最小、最大、求和、平均、统计所有@Testpublic void test04() {List<Employee> list = List();// 计数Long count = list.stream().unting());System.out.println(count);// 最小Optional<Employee> min = list.stream().collect(Collectors.minBy((o1, o2) -> o1.getAge() - o2.getAge()));System.out.());// 最大Optional<Employee> max = list.stream().collect(Collectors.maxBy((o1, o2) -> o1.getAge() - o2.getAge()));System.out.());// 求和int sum = list.stream().collect(Collectors.summingInt(Employee::getAge));System.out.println(sum);// 平均double avg = list.stream().collect(Collectors.averagingInt(Employee::getAge));System.out.println(avg);// 统计所有IntSummaryStatistics summary = list.stream().collect(Collectors.summarizingInt(Employee::getAge));System.out.println(summary);}/*// 归纳public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op) {}public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op) {}public static <T, U> Collector<T, ?, U> reducing(U identity, Function<? super T, ? extends U> mapper, BinaryOperator<U> op) {}*/// 4、归纳@Testpublic void test05() {List<Employee> employees = List();Integer sum1 = employees.stream().map(Employee::getAge).ducing(100, Integer::sum));System.out.println(sum1);Optional<Integer> sum2 = employees.stream().map(Employee::getAge).ducing(Integer::sum));System.out.());Integer sum3 = employees.stream().map(Employee::getSalary).ducing(0, Double::intValue, Integer::sum));System.out.println(sum3);}/*// 5.1、分组:返回 Mappublic static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T,? extends K> classifier) {}public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream) {}public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,Supplier<M> mapFactory,Collector<? super T, A, D> downstream) {}*/@Testpublic void test06() {List<Employee> employees = List();
// Map<String, List<Employee>> map = employees.stream().upingBy(Employee::getGender));
// map.forEach((k, v) -> System.out.println(k + "::" + v));
// Map<String, Map<Integer, List<Employee>>> map2 = employees.stream().upingBy(Employee::getGender, upingBy(Employee::getAge)));
// map2.forEach((k, v) -> {
// System.out.println(k);
// v.forEach((k1, v1) -> System.out.println("t" + k1 + "::" + v1));
// });HashMap<String, Map<Integer, List<Employee>>> map3 = employees.stream().upingBy(Employee::getGender, HashMap::new, upingBy(Employee::getAge)));map3.forEach((k, v) -> {System.out.println(k);v.forEach((k1, v1) -> System.out.println("t" + k1 + "::" + v1));});}/*// 6、分区public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {}public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,Collector<? super T, A, D> downstream) {}*/@Testpublic void test07() {List<Employee> employees = List();
// Map<Boolean, List<Employee>> map1 = employees.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 4500.0D));
// System.out.println("薪资是否超过 4500:");
// map1.forEach((k, v) -> {
// System.out.println(k + "::" + v);
// });Map<Boolean, Map<Boolean, List<Employee>>> map2 = employees.stream().collect(Collectors.partitioningBy(e -> e.getSalary() >= 4500.0D, Collectors.partitioningBy(e -> e.getAge() >= 20)));System.out.println("薪资是否超过 4500");map2.forEach((k, v) -> {System.out.println(k);System.out.println("t年龄是否超过 20");v.forEach((k1, v1) -> {System.out.println("t" + k1 + "::" + v1);});});}/*// 7、映射public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {}*/@Testpublic void test08() {List<Employee> list = List();Map<Boolean, List<Integer>> map = list.stream().collect(Collectors.mapping(Employee::getAge, Collectors.partitioningBy(integer -> integer >= 20)));map.forEach((k, v) -> System.out.println(k + "::" + v));}/*// 8、收集,然后执行 Functionpublic static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) {}*/@Testpublic void test09() {List<Employee> list = List();Object[] collect = list.stream().llectingAndThen(Collectors.mapping(Employee::getGender, List()), ls -> ls.toArray()));System.out.println(collect.length);}
}
本文发布于:2024-02-01 09:37:10,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170675143235706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |