首页
关于
友链
Search
1
wlop 4K 壁纸 4k8k 动态 壁纸
1,468 阅读
2
Nacos持久化MySQL问题-解决方案
932 阅读
3
Docker搭建Typecho博客
751 阅读
4
滑动时间窗口算法
728 阅读
5
Nginx反向代理微服务配置
699 阅读
生活
解决方案
JAVA基础
JVM
多线程
开源框架
数据库
前端
分布式
框架整合
中间件
容器部署
设计模式
数据结构与算法
安全
开发工具
百度网盘
天翼网盘
阿里网盘
登录
Search
标签搜索
java
javase
docker
java8
springboot
thread
spring
分布式
mysql
锁
linux
redis
源码
typecho
centos
git
map
RabbitMQ
lambda
stream
少年
累计撰写
189
篇文章
累计收到
24
条评论
首页
栏目
生活
解决方案
JAVA基础
JVM
多线程
开源框架
数据库
前端
分布式
框架整合
中间件
容器部署
设计模式
数据结构与算法
安全
开发工具
百度网盘
天翼网盘
阿里网盘
页面
关于
友链
搜索到
4
篇与
的结果
2022-09-15
JAVA8-Optional API
Optional API一、Optional创建方式前置条件:Insurance对象:public class Insurance { private String name; public String getName() { return name; } }1、empty特点:使用get()方法时会抛出异常:No value present范例:Optional<Insurance> emptyOptional = Optional.<Insurance>empty();使用get()获取结果:抛出异常emptyOptional.get();输出结果:Exception in thread "main" java.util.NoSuchElementException: No value present at java.base/java.util.Optional.get(Optional.java:148)2、of特点:使用get(),不会抛异常范例:Optional<Insurance> ofInsurance = Optional.of(new Insurance()); ofInsurance.get();3、ofNullable特点:上面两者综合,为null是掉empty,不为空调of。3.1、为null时,调get()抛出异常范例: Optional<Insurance> ofNullableOptionalNull = Optional.ofNullable(null); ofNullableOptionalNull.get();输出结果:Exception in thread "main" java.util.NoSuchElementException: No value present3.2、不为null时,调get()不报错范例: Optional<Insurance> ofNullableOptionalNotNull = Optional.ofNullable(new Insurance()); ofNullableOptionalNotNull.get();二、orElseGet、orElse、orElseThrow不管那种方式创建,都适用这几个方法。1、orElseGet说明:不为null就返回值,为null返回一个构造的对象supplier范例:Insurance orElseGetInsurance = ofNullableOptionalNull.orElseGet(Insurance::new); System.out.println(orElseGetInsurance);2、orElse说明:不为null就返回值,否则返回一个引用范例:Insurance orElseInsurance = ofNullableOptionalNull.orElse(new Insurance()); System.out.println(orElseInsurance);3、orElseThrow说明:不为null就返回值,否则返回一个异常对象范例:Insurance orElseThrowInsurance = ofNullableOptionalNull.orElseThrow(RuntimeException::new);输出结果:抛出运行时异常Exception in thread "main" java.lang.RuntimeException at java.base/java.util.Optional.orElseThrow(Optional.java:408)4、orElseThrow说明:不为null就返回值,否则返回一个自定义异常对象范例:ofNullableOptionalNull.orElseThrow(() -> new RuntimeException("yanxizhu Exception"));输出结果:抛出自定义异常Exception in thread "main" java.lang.RuntimeException: yanxizhu Exception三、filter先判断传入predicate是否null,让然后判断predicate传入字段是否存在,不存在:返回this。存在:判断predicate条件是否成立,成立:返回this,不成立:返回空。源码: public Optional<T> filter(Predicate<? super T> predicate) { //1、判断传入参数predicate是否为null Objects.requireNonNull(predicate); //2、判断t.getName是否存在, if (!isPresent()) { //2.1、不存在,返回predicate return this; } else { //2.2、存在:判断predicate条件是否成立,成立返回this,不成立返回empty() return predicate.test(value) ? this : empty(); } }requireNonNull()源码:判断传入T是否为null public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }范例:使用前创建Optional对象:1、创建Optinal,get()会抛出异常 Optional<Insurance> emptyOptional = Optional.<Insurance>empty(); 2、of创建,get(),不会抛异常 Optional<Insurance> ofInsurance = Optional.of(new Insurance()); 3、ofNullable:上面两者综合 3.1、为null时,调get()抛出异常:No value present Optional<Insurance> ofNullableOptionalNull = Optional.ofNullable(null); 3.2、不为null时,调get()不报错 Optional<Insurance> ofNullableOptionalNotNull = Optional.ofNullable(new Insurance());使用demo1: Optional<Insurance> insurance = emptyOptional.filter(t -> t.getName() == null); Optional<Insurance> insurance = emptyOptional.filter(t -> t.getName() != null); insurance.get();结果://调用get(),都会报错:No value present: 因为name字段不存在使用demo2:范例1:Optional<Insurance> insurance = ofInsurance.filter(t -> t.getName() == null); insurance.get(); 结果://不报错,因为name字段存在,且满足name==null范例2:Optional<Insurance> insurance = ofInsurance.filter(t -> t.getName() != null); insurance.get(); 结果://报错,因为name虽然存在,但是name!=null,不成立,会返回empty空,使用get()时就会抛出异常:No value present使用demo3: Optional<Insurance> insurance = ofNullableOptionalNull.filter(t -> t.getName() != null); Optional<Insurance> insurance = ofNullableOptionalNull.filter(t -> t.getName() == null); insurance.get();结果://都报错:ofNullableOptional,会走empty创建的Optional,字段不存在,直接get获取值为空,报错:No value present使用demo4:范例1:Optional<Insurance> insurance = ofNullableOptionalNotNull.filter(t -> t.getName() == null); insurance.get(); 结果://不会报错,走of方法创建的Optional,name字段存在,且name==null,所以不报错范例2:Optional<Insurance> insurance = ofNullableOptionalNotNull.filter(t -> t.getName() != null); insurance.get(); 结果://报错,因为虽然name存在,但是name!=null不成立,返回empty,get()就报错了filter,总结:使用时不确定是否为empty,所以直接使用ofNullableOptional创建Optional.四、map使用任何方式创建的Opional,map会将结果再包装成Optionla。范例: //map使用 Optional<String> stringOptional = ofNullableOptionalNotNull.map(t -> t.getName()); //有值则返回,没值则返回给定值 System.out.println(stringOptional.orElse("-1")); //判断值是否存在 System.out.println(stringOptional.isPresent()); //存在值,则打印输出,没有值,不打印。 stringOptional.ifPresent(System.out::println);五、flatMap不会将结果再包装成Optional范例:前置条件 @Data public class Cat { private Optional<Eat> eat; } @Data public class Eat { private String foodName; private Integer weight; }使用: //创建Optional对象 Optional<Cat> cat = Optional.ofNullable(new Cat()); //map将结果包装成Optional Optional<Optional<Eat>> eat = cat.map(c -> c.getEat()); //flatMap不会 Optional<Eat> eat1 = cat.flatMap(c -> c.getEat());map与flatMap区别:map将结果包装成Optional,flatMap不会。六、实列实列1、获取值之前判断值是否为空 public static String getInsuranceName(Insurance insurance) { Optional<String> optional = Optional.ofNullable(insurance).map(Insurance::getName); return optional.orElse("-1"); }实列2、根据用户拿到保险名字package com.example.study.java8.optional; import java.util.Optional; /** * 根据用户拿到保险名字 */ public class NullPointerException { public static void main(String[] args) { //肯定会包空指针异常 // String insuranceNameByPerson = getInsuranceNameByPerson(new Person()); //原始写法,做了空指针判断 String insuranceNameByCheckPerson = getInsuranceNameByCheckPerson(new Person()); // System.out.println(insuranceNameByCheckPerson); //Opional写法 String insuranceNameByOptional = getInsuranceNameByOptional(null); System.out.println(insuranceNameByOptional); } //Opional写法 public static String getInsuranceNameByOptional(Person person) { return Optional.ofNullable(person) .map(Person::getCar) .map(Car::getInsurance) .map(Insurance::getName) .orElse("-1"); } //flatMap不会把结果包装成Optional,map会。 //原始写法判断 public static String getInsuranceNameByCheckPerson(Person person) { if(null != person) { if(null != person.getCar()) { Car car = person.getCar(); if (null != car) { Insurance insurance = car.getInsurance(); if (null != insurance) { return insurance.getName(); } } } } return "UNKNOWN"; } public static String getInsuranceNameByPerson(Person person){ return person.getCar().getInsurance().getName(); } }
2022年09月15日
145 阅读
0 评论
3 点赞
2022-09-07
JAVA8-Stream创建
创建Stream创建Stream方式:创建Stream的方式1、通过Collection2、通过values3、通过Arrays4、通过file5、通过iterate创建,无限的创建6、通过Generate创建7、自定义Supplier,创建Stream使用范例1、Collection创建,输出值顺序与之前放入值顺序一致。范例: /** * 通过Collection创建Stream,数据顺序和放入顺序一致 * @return */ public static Stream<String> createStreamByCollection(){ List<String> list = Arrays.asList(new String("Hello"), new String("world"), new String("please")); return list.stream(); }2、values创建,输出值顺序与之前放入值顺序一致。范例: /** * 通过values创建Stream,顺序一直 * @return */ public static Stream<String> createStreamByValues(){ return Stream.of("Hello","world","please"); }3、Arrays创建,输出值顺序与之前放入值顺序一致。范例: /** * 3、通过Arrays创建,顺序一致 * @return */ public static Stream<String> createStreamByArrays(){ return Arrays.stream(new String[]{"Hello","world","please"}); }4、File创建范例: /** * 4、通过file创建 * @return */ public static Stream<String> createStreamByFile(){ Path path = Paths.get("D:\\software\\workspace\\IdeaProjects\\study\\study-java8\\src\\main\\java\\com\\example\\study\\java8\\streams\\CreateStream.java"); try { Stream<String> stream = Files.lines(path); return stream; } catch (IOException e) { throw new RuntimeException(e.getMessage()); } }5、iterate无限的创建范例: /** * 5、通过iterate创建,无限的创建 * @return */ public static Stream<Integer> createStreamByIterate(){ return Stream.iterate(0, n->n+2).limit(10); } 6、Generate创建范例: /** * 6、通过Generate创建 * @return */ public static Stream<Double> crateStreamByGenerate(){ return Stream.generate(Math::random).limit(10); }7、自定义Supplier,创建Stream范例: /** * 自定义Supplier,创建Stream * @return */ public static Stream<Obj> createStreamByDefine(){ return Stream.generate(new ObjSupplier()).limit(10); } static class ObjSupplier implements Supplier<Obj> { int index =0; Random random = new Random(System.currentTimeMillis()); @Override public Obj get() { index = random.nextInt(100); return new Obj(index, "Name->"+index); } } @Data @AllArgsConstructor @NoArgsConstructor @ToString static class Obj{ private Integer id; private String name; }熟悉创建Stream后,就是使用其api进行开发了。
2022年09月07日
108 阅读
0 评论
2 点赞
2022-09-06
JAVA8方法推导
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); } } 自定义函数式接口package com.example.study.java8.InterfaceFunction; /** * 自定义多个参数函数接口,创建对象 */ @FunctionalInterface public interface CustomThreeFunctionalInterface<T, U, K, R> { R apply(T t, U u, K k); } ComplexApplepackage com.example.study.java8.InterfaceFunction; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * 多个参数,构造方法推导 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class ComplexApple { private String color; private Integer weight; private String name; } 主要讲解了,Lambda方法推导的常见用法。
2022年09月06日
119 阅读
0 评论
3 点赞
2022-09-06
Java8-functionInterface
Lambda表达式用法用户范例package com.example.study.java8.InterfaceFunction; /** * lambda表达式用法 */ public class LambdaUsage { public static void main(String[] args) { Runnable runnable1 = ()-> System.out.println("hello"); Runnable runnable2 = new Runnable() { @Override public void run() { System.out.println("hello"); } }; process(runnable1); process(runnable2); process(()-> System.out.println("hello")); } public static void process(Runnable runnable){ runnable.run(); } } 学习目标一、Predicate:诊断,返回boolean类型@FunctionalInterface public interface Predicate {/** * 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);二、Consumer:消费者,没有返回类型@FunctionalInterface public interface Consumer {/** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t);三、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);四、Supplier:生成者:返回一个对象@FunctionalInterface public interface Supplier {/** * Gets a result. * * @return a result */ T get();详细说明1、Predicate详细用法范例: package com.example.study.java8.InterfaceFunction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiPredicate; import java.util.function.IntPredicate; import java.util.function.Predicate; /** * Lambda表达式的使用:Prodicate用法 */ public class LambdaUsagePredicate { public static void main(String[] args) { 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)); //Predicate用法 List<Apple> filterList = filter(list, apple -> apple.getColor().equals("green")); for (Apple apple : filterList) { System.out.println(apple.toString()); } System.out.println("============================"); //其它类似Predicate用法 //IntegerPredicate用法 List<Apple> filterByWeight = predicateByWeight(list, weight -> weight == 60); for (Apple apple : filterByWeight) { System.out.println(apple.toString()); } System.out.println("============================"); //BiPredicate用法 List<Apple> biPredicateResult = biPredicateByColorAndWeight(list, (color, weight) -> { return color.equals("green") && weight == 60; }); for (Apple apple : biPredicateResult) { System.out.println(apple.toString()); } } //1、Predicate:诊断的用法 public static List<Apple> filter(List<Apple> sources, Predicate<Apple> predicate) { List<Apple> result = new ArrayList<>(); for (Apple apple : sources) { if (predicate.test(apple)) { result.add(apple); } } return result; } //2、其它类似Predicate用法 //IntegerPredicate用法 public static List<Apple> predicateByWeight(List<Apple> source, IntPredicate intPredicate) { List<Apple> result = new ArrayList<>(); for (Apple apple : source) { if (intPredicate.test(apple.getWeight())) { result.add(apple); } } return result; } //3、带2个参数的BiPredicate用法 public static List<Apple> biPredicateByColorAndWeight(List<Apple> source, BiPredicate<String, Integer> biPredicate) { List<Apple> result = new ArrayList<Apple>(); for (Apple apple : source) { if (biPredicate.test(apple.getColor(), apple.getWeight())) { result.add(apple); } } return result; } } 2、Consumer详细用法范例: package com.example.study.java8.InterfaceFunction; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Lambda表达式:Consumer用法 */ public class LambdaUasgeConsumer { public static void main(String[] args) { 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)); //1个参数调用 simpleUsageConsumer(list, apple -> System.out.println(apple.toString())); System.out.println("========================"); twoArgsUsageConsumer("我买了水果",list, (apple, name)->{ System.out.println(name+",颜色:"+apple.getColor()+"\t 重量:"+apple.getWeight()); }); } //1、一个参数用法 public static void simpleUsageConsumer(List<Apple> source, Consumer<Apple> consumer) { for (Apple apple : source) { consumer.accept(apple); } } //2、两个参数用法 public static void twoArgsUsageConsumer(String name, List<Apple> source, BiConsumer<Apple, String> consumer) { for (Apple apple : source) { consumer.accept(apple, name); } } } 3、Funcation详细用法范例:package com.example.study.java8.InterfaceFunction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.IntFunction; /** * Lambda表达式:Funcation用法 */ public class LambdaUsageFuncation { public static void main(String[] args) { 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)); //1、2个参数调用 List<String> stringsUsageFuncation = simpleUsageFuncation(list, apple -> apple.getColor() + ":颜色"); for(String color: stringsUsageFuncation){ System.out.println(color); } System.out.println("============================"); //2、其它用法IntFuncation调用 List<Integer> integerList = intUsageFuncation(list, weight-> weight*20); for(Integer i : integerList){ System.out.println(i); } System.out.println("=============================="); //3、3个参数调用 Apple newApple = threeeUsageFuncation("彩色", 178, (newColor, newInteger) -> { return new Apple(newColor, newInteger); }); System.out.println(newApple.toString()); } //1、2个参数 简单用法 public static List<String> simpleUsageFuncation(List<Apple> source, Function<Apple, String> function){ List<String > result = new ArrayList<>(); for(Apple apple:source){ result.add(function.apply(apple)); } return result; } //2、其它用法IntFuncation public static List<Integer> intUsageFuncation(List<Apple> source, IntFunction<Integer> function){ List<Integer > result = new ArrayList<>(); for(Apple apple:source){ result.add(function.apply(apple.getWeight())); } return result; } //3、3个参数用法 public static Apple threeeUsageFuncation(String newColor, Integer newWeight, BiFunction<String, Integer, Apple> biFunction){ return biFunction.apply(newColor, newWeight); } } 4、Supplier详细用户范例:package com.example.study.java8.InterfaceFunction; import java.util.function.Supplier; /** * Lamdba表达式之Supplier用法 */ public class LambdaUsageSupplier { public static void main(String[] args) { //范例1 Supplier<String> stringSuppier = String::new; System.out.println(stringSuppier.get().getClass()); System.out.println("====================="); //范例2 Apple apple = createApple(() -> { return new Apple("五颜六色", 200); }); System.out.println(apple.toString()); } public static Apple createApple(Supplier<Apple> supplier){ return supplier.get(); } } 注意:参数类型package com.example.study.java8.InterfaceFunction; /** * 参数类型注意 */ public class ArgsCase { public static void main(String[] args) { int i =0; Runnable runnable = new Runnable() { @Override public void run() { //i会报错提示: //Variable 'i' is accessed from within inner class, needs to be final or effectively final // i++; } }; i++; //Lambda表达式 Runnable runnable1 = ()->{ //i同样报错提示: //Variable used in lambda expression should be final or effectively final // System.out.println(i); }; i++; } }
2022年09月06日
170 阅读
0 评论
5 点赞