2022 年
7 篇记录
Lambda方法推导详细解析 什么情况下可以进行方法推导? 类的方法(静态方法)
对象的方法
构造方法
自定义函数式接口
范例: package com.example.study.java8.InterfaceFunction; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; /** * 方法推导 * 什么情况下可以进行方法推导: * 1、类的方法(静态方法) * 2、对象的方法 * 3、构造方法 */ public class MethodReferenceUsageDemoOne { public static void main(String[] args) { //方法推导,范例一:类的方法 //原始写法 Consumer<String> consumer = s-> System.out.println(s); genericityConsumer(consumer, "hello"); //1、进化一 genericityConsumer(s->System.out.println(s), "world"); //2、进化二 genericityConsumer(System.out::println, "nice"); System.out.println("==========================="); //方法推导,范例二:类的方法 List<Apple> list = Arrays.asList(new Apple("red", 10) , new Apple("red", 60) , new Apple("blue", 40) , new Apple("black", 30) , new Apple("green", 80) , new Apple("blue", 90) , new Apple("green", 60) , new Apple("green", 50) , new Apple("red", 20)); System.out.println(list); list.sort((oneParameter,twoParameter)->oneParameter.getColor().compareTo(twoParameter.getColor())); System.out.println(list); System.out.println("============排序另一种写法==============="); //排序另一种写法 List<Apple> list2= Arrays.asList(new Apple("red", 10) , new Apple("red", 60) , new Apple("blue", 40) , new Apple("black", 30) , new Apple("green", 80) , new Apple("blue", 90) , new Apple("green", 60) , new Apple("green", 50) , new Apple("red", 20)); System.out.println(list2); list2.sort(Comparator.comparing(Apple::getColor)); //排序说明: //1、匿名内部类 //2、上面第一种写法 //3、上面第二种写法 //代码越来越简单 System.out.println("==========================="); //方法推导,范例三:类的方法 //原始写法 list.stream().forEach(apple->System.out.println(apple)); System.out.println("==========================="); //进化1 list.stream().forEach(System.out::println); System.out.println("==========================="); //方法推导,范例四:类的方法 //原始写法 Integer integer = Integer.parseInt("123"); System.out.println(integer); System.out.println("==========================="); //进化 Function<String, Integer> function = Integer::parseInt; Integer integerTwo = function.apply("321"); System.out.println(integerTwo); System.out.println("==========================="); //方法推导,范例五:对象的方法 BiFunction<String, Integer, Character> stringIntegerCharacterBiFunction = String::charAt; Character character = stringIntegerCharacterBiFunction.apply("Hello", 1); System.out.println(character); System.out.println("==========================="); //方法推导,范例六:构造方法,1个参数 Supplier<String> supplier = String::new; String str = supplier.get(); System.out.println(str.getClass()); System.out.println("==========================="); //方法推导,范例七:构造方法,2个参数 //说明:Apple::new; 就是掉构造方法,自动推导参数和类型 BiFunction<String,Integer,Apple> appleBiFunction = Apple::new; Apple apple = appleBiFunction.apply("red", 50); System.out.println(apple); System.out.println("==========================="); //方法推导,范例八:构造方法-自定义FunctionalInterface接口,多个参数 CustomThreeFunctionalInterface<String,Integer,String,ComplexApple> appleSupplier = ComplexApple::new; ComplexApple complexApple = appleSupplier.apply("苹果",20,"green"); System.out.println(complexApple); } /** * 泛型Consumer * @param consumer * @param t * @param <T> */ public static <T> void genericityConsumer(Consumer<T> consumer, T t){ consumer.accept(t); } } 自定义函数式接口
#java#Lambda#流式管道操作#自定义函数式接口#可连续操作#流式管#java8#jdk8#lambda#stream
自定义Collector 实现Collector接口 package com.example.study.java8.collector; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; /** * 自定义Collector * T:元素类型 * List<T>:要创建的类型 * List<T>:最后要返回的类型 */ public class ToListCollector<T> implements Collector<T, List<T>, List<T>> { private void log(final String log) { System.out.println(Thread.currentThread().getName()+"-"+log); } //一定时可变的supplier,不是固定值 @Override public Supplier<List<T>> supplier() { log("supplier"); return ArrayList::new; } //要进行的操作 @Override public BiConsumer<List<T>, T> accumulator() { log("accumulator"); return List::add; } //将结果整合 @Override public BinaryOperator<List<T>> combiner() { log("combiner"); return (list1,list2)->{ list1.addAll(list2); return list1; }; } //返回结果 @Override public Function<List<T>, List<T>> finisher() { log("finisher"); // return t->t; return Function.identity(); } //特征值:CONCURRENT-并行,UNORDERED-排序,IDENTITY_FINISH-入参就出参 @Override public Set<Characteristics> characteristics() { log("characteristics"); return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.CONCURRENT)); } } 使用测试 package com.example.study.java8.collector; import java.util.Arrays; import java.util.List; import java.util.stream.Collector; /** * 使用自定义Collector测试 */ public class CustomToListCollector { public static void main(String[] args) { String[] arrs = new String[]{"chinese","japanse","english","freach","Korean"}; //测试 //对应接口中的: //Supplier<A> supplier(), BiConsumer<A, T> accumulator(),Function<A, R> finisher(); Collector<String, List<String>, List<String>> collector = new ToListCollector<String>(); List<String> list = Arrays.stream(arrs).filter(s -> s.length() > 6).collect(collector); System.out.println(list); System.out.println("================================"); //parallelStream(),并行使用测试 List<String> parallelList = Arrays.asList(new String[]{"chinese", "japanse", "english", "freach", "Korean"}) .parallelStream() .filter(s -> s.length() > 6) .collect(collector); System.out.println(parallelList); } } 输出结果 main-supplier main-accumulator main-combiner main-characteristics main-characteristics [chinese, japanse, english] ================================ main-characteristics main-characteristics main-supplier main-accumulator main-combiner main-characteristics main-characteristics [chinese, japanse, english] 由于数据量少,并没有出现并行。
#java#Collector#自定义Collector#流式管道操作#操作中断#可连续操作#流式管#java8#jdk8#lambda
Stream基本使用及特点 Stream说明 Stream操作分为:2组,//注意,流式管道操作,只能操作一次,否则报错。
1、可连续操作:
filter, map, and limit can be connected together to form a pipeline. 2、操作中断
collect causes the pipeline to be executed and closes it. 使用范例: package com.example.study.java8.streams; import java.util.*; import java.util.stream.Stream; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; /** * Stream使用 * Stream操作分为:2组,//注意,流式管道操作,只能操作一次,否则报错 * You can see two groups of operations: * 1、可连续操作 * filter, map, and limit can be connected together to form a pipeline. * 2、操作中断 * collect causes the pipeline to be executed and closes it. */ public class SimpleStream { public static void main(String[] args) { List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT), new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER), new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH)); Stream<Dish> stream = menu.stream(); stream.forEach(System.out::println); //注意,流式管道操作,只能操作一次,否则报错 //stream has already been operated upon or closed // stream.forEach(System.out::println); System.out.println("===================================="); //原始调用 List<String> namesByCollections = getDishNamesByCollections(menu); namesByCollections.stream().forEach(System.out::println); System.out.println("===================================="); //lambda stream调用 List<String> lambdaStreamNames = lambdaStream(menu); lambdaStreamNames.stream().forEach(System.out::println); } //原始写法 public static List<String> getDishNamesByCollections(List<Dish> menu) { List<Dish> caloriesDis = new ArrayList<>(); for (Dish dish : menu) { if (dish.getCalories() < 400) { caloriesDis.add(dish); } } Collections.sort(caloriesDis, (dish1, dish2) -> { return Integer.compare(dish1.getCalories(), dish2.getCalories()); }); List<String> names = new ArrayList<>(); for(Dish dish : caloriesDis){ names.add(dish.getName()); } return names; } //stream lambda处理 public static List<String> lambdaStream(List<Dish> menu){ return menu.stream().filter(dis -> dis.getCalories() < 400) .sorted(comparing(Dish::getCalories)) .map(Dish::getName).collect(toList()); } } 主要掌握Stream接口中常用方法。 Stream源码:
#java#Stream#基本用法#流式管道操作#操作中断#可连续操作#流式管#java8#jdk8#lambda
针对<实现一个异步基于事件回调的Future程序> 用CompletableFuture进行改进。
代码示例:
package com.example.study.java8.completableFutures; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * CompletableFuture 基本用法 */ public class CompletableFutureInAction1 { private final static Random RANDOM = new Random(System.currentTimeMillis()); public static void main(String[] args) throws ExecutionException, InterruptedException { //实际开发中,一般不直接new,而是使用工厂创建 // CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(); CompletableFuture<Double> completableFuture = new CompletableFuture<>(); new Thread(()->{ double value = get(); completableFuture.complete(value); }).start(); //不会阻塞程序执行 System.out.println("===========no====block====.."); //1、后面获取程序执行结果 // Optional.ofNullable(completableFuture.get()).ifPresent(System.out::println); //2、执行完后,通过回调自动返回结果 completableFuture.whenComplete((v,t)->{ Optional.ofNullable(v).ifPresent(System.out::println); Optional.ofNullable(t).ifPresent(x->x.printStackTrace()); }); } private static double get(){ try { Thread.sleep(RANDOM.nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } return RANDOM.nextDouble(); } } 输出结果:
#java#CompletableFuture#基本用法#LocalTime#Instant#Duration#Period#java8#jdk8#lambda
通过线程池性能稳定,也可以获取执行结果,并捕获异常。但是,在业务复杂情况下,一个异步调用可能会依赖于另一个异步调用的执行结果。因此我们可以使用completableFuture 异步编排方案。
比如:一个业务场景,需要同时获取多个数据,如果同步线程挨个执行,则需要时间为所有线程执行时间的总和。
如果我们使用异步线程执行,所需时间则为耗时最长那个异步线程的执行时间。
如果多个异常线程之间还存在依赖关系,比如线程3需要线程1的执行结果,线程6依赖线程3、线程2,那这个问题怎么解决呢。那就可以使用completableFuture 异步编排方案实现。
注意:completableFuture 是jdk1.8之后添加的一个功能。
CompletableFuture接口:
public class CompletableFuture<T> implements Future<T>, CompletionStage<T> { public interface Future<V> { 以前用到的FutureTask就是用到的Future可以得到返回结果
public class FutureTask<V> implements RunnableFuture<V> { public interface RunnableFuture<V> extends Runnable, Future<V> { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ void run(); } Future可以得到返回结果
#java#CompletableFuture#异步编排#LocalTime#Instant#Duration#Period#java8#jdk8#lambda
JAVA8-Date and Time API: LocalDate, LocalTime, Instant, Duration, Period 旧API问题 1、代码不清晰,一下看不出要转换的日期。
**2、Date日期中还包含了时间 **
3、多线程情况下会报错。
代码重现:
package com.example.study.java8.datetime; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) throws ParseException { //122格林威治时间 11月 23日期 //问题:不能清晰表示日期 Date date = new Date(122, 11, 23); System.out.println(date); //多线程情况下会出现一些问题: //30个线程,每个线程下循环100次,执行时间格式转换。 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); for (int i = 0; i < 30; i++) { new Thread(() -> { for (int j = 0; j < 100; j++) { Date parseDate = null; try { parseDate = sdf.parse("20221123"); } catch (ParseException e) { e.printStackTrace(); } System.out.println(parseDate); } }).start(); } } } 输出结果:
#java#CompletableFuture#LocalDate#LocalTime#Instant#Duration#Period#java8#jdk8#lambda
AVA8-CompletableFuture常用API:runAfterBoth、applyToEither、acceptEither 、runAfterEither 、allOf、anyOf 1、runAfterBoth :2个CompletableFuture都执行完后,再执行其它操作 package com.example.study.java8.completableFutures.api; import java.util.concurrent.CompletableFuture; public class CompletableFutureAction2 { public static void main(String[] args) throws InterruptedException { //API-- 1、runAfterBoth: 2个都执行完后,再执行其它操作 CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + "this is runing 1......"); return 1; }) .runAfterBoth(CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + "this is runing 2......"); return 2; }), () -> System.out.println("done")); //为了防止主线程结束后,守护线程被关闭,模拟修改10000毫秒 Thread.sleep(10000); } } 输出结果:
#java#CompletableFuture#applyToEither#acceptEither#runAfterEither#allOf#anyOf#java8#jdk8#lambda