首页
关于
友链
Search
1
wlop 4K 壁纸 4k8k 动态 壁纸
1,470 阅读
2
Nacos持久化MySQL问题-解决方案
932 阅读
3
Docker搭建Typecho博客
752 阅读
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
多线程
开源框架
数据库
前端
分布式
框架整合
中间件
容器部署
设计模式
数据结构与算法
安全
开发工具
百度网盘
天翼网盘
阿里网盘
页面
关于
友链
搜索到
3
篇与
的结果
2022-09-18
JAVA8-Collectors API:averaging、collectingAndThen、counting、groupingBy
JAVA8-Collectors API:averaging、collectingAndThen、counting、groupingBy前置数据 public static final 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));范例:1、averagingDouble 求平均值 public static void testAveragingDouble(){ System.out.println("testAveragingDouble"); //用reduce聚合求和 Optional.ofNullable(menu.stream().map(Dish::getCalories).reduce(Integer::sum)).get().ifPresent(System.out::println); //用collectors averagingDouble求平均值 Optional.ofNullable(menu.stream().collect(averagingDouble(Dish::getCalories))).ifPresent(System.out::println); }输出结果:testAveragingDouble 4200 466.66666666666672、averagingInt 求平均值 public static void testAveragingInt(){ System.out.println("testAveragingInt"); //用collectors averagingDouble求平均值 Optional.ofNullable(menu.stream().collect(averagingInt(Dish::getCalories))).ifPresent(System.out::println); }输出结果:testAveragingInt 466.66666666666673、averagingLong 求平均值 public static void testAveragingLong(){ System.out.println("testAveragingLong"); //用collectors averagingLong求平均值 Optional.ofNullable(menu.stream().collect(averagingLong(Dish::getCalories))).ifPresent(System.out::println); }输出结果:testAveragingLong 466.66666666666674、collectingAndThen(收集数据,处理数据),将搜集结果,再做处理。4.1、CollectingAndThen 求平均数后,拼接一句话 Optional.ofNullable(menu.stream().collect(Collectors.collectingAndThen(averagingInt(Dish::getCalories),a->"This is Calories eques = "+a))).ifPresent(System.out::println);输出结果:testCollectingAndThen This is Calories eques = 466.66666666666674.2、获取MEAT类,之后再往里面加入其它类型 List<Dish> collect = menu.stream().filter(m -> Dish.Type.MEAT.equals(m.getType())).collect(toList()); collect.add(new Dish("回锅肉", true, 550, Dish.Type.OTHER)); collect.stream().forEach(System.out::println);输出结果:Dish{name='pork', vegetarian=false, calories=800, type=MEAT} Dish{name='beef', vegetarian=false, calories=700, type=MEAT} Dish{name='chicken', vegetarian=false, calories=400, type=MEAT} Dish{name='回锅肉', vegetarian=true, calories=550, type=OTHER}4.3、CollectingAndThen 如果想将收集结果设置为不可修改 List<Dish> meatCollect = menu.stream().filter(m -> Dish.Type.MEAT.equals(m.getType())).collect(collectingAndThen(toList(), Collections::unmodifiableList)); //修改时就会报错:Exception in thread "main" java.lang.UnsupportedOperationException meatCollect.add(new Dish("回锅肉", true, 550, Dish.Type.OTHER)); collect.stream().forEach(System.out::println);输出结果:Exception in thread "main" java.lang.UnsupportedOperationException5、counting 统计 返回Long类型 public static void testCounting(){ System.out.println("testCounting"); Optional.ofNullable(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println); }输出结果:testCounting 96、groupingBy 分组public static void testGroupingByFunction(){ System.out.println("testGroupingByFunction"); Optional.of(menu.stream().collect(Collectors.groupingBy(Dish::getType))).ifPresent(System.out::println); }输出结果:testGroupingByFunction {OTHER=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}], MEAT=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}], FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}]} 7、groupingBy 分组后统计 public static void testGroupingByFunctionAndCollector(){ System.out.println("testGroupingByFunctionAndCollector"); Optional.of(menu.stream().collect(Collectors.groupingBy(Dish::getType,counting()))).ifPresent(System.out::println); }输出结果:testGroupingByFunctionAndCollector {OTHER=4, MEAT=3, FISH=2}8、groupingBy 分组后求平均值,默认是HashMap,通过groupingBy修改返回类型 public static void testGroupingByFunctionAndSuppilerAndCollector(){ System.out.println("testGroupingByFunctionAndSuppilerAndCollector"); Map<Dish.Type, Double> map = Optional.of(menu.stream().collect(groupingBy(Dish::getType, averagingInt(Dish::getCalories)))).get(); //默认是返回HashMap类型 Optional.ofNullable(map.getClass()).ifPresent(System.out::println); TreeMap<Dish.Type, Double> newMap = Optional.of(menu.stream().collect(groupingBy(Dish::getType, TreeMap::new, averagingInt(Dish::getCalories)))).get(); //groupingBy:修改返回类型为TreeMap Optional.ofNullable(newMap.getClass()).ifPresent(System.out::println); }输出结果:testGroupingByFunctionAndSuppilerAndCollector class java.util.HashMap class java.util.TreeMap
2022年09月18日
163 阅读
0 评论
5 点赞
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 点赞
2022-09-05
Java8-Lambda语法
Lambda表达式一、lambda语法参数列表 lambda body部分 (o1,o2)->o1.getWeight().compareTo(o2.getWeight());二、 合法lamdba表达式1、s -> s.length(); 或者 (String s) -> s.length(); 2、apple -> apple.getColor().equals("great"); 或者 (Apple apple) -> apple.getColor().equals("great"); 3、(int x, int y) -> { System.out.println(x); System.out.println(y); }; 4、() -> 12; 5、()-{}; 6、()->“hello” 或者 ()->{return "hello"}三、语法总结语法一、(参数列表) -> 表达式 语法二、(参数列表) -> {语句;}有效lambda表达式1、() -> {} 2、() -> "hello" 或者 ()->{reurn "hello"} 3、(String str) -> {return "hello"} 或者 (String str) -> "hello";无效lambda表达式(integer i)->{return "错误示范"+i}四、代码说明package com.example.study.java8.InterfaceFunction; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Predicate; /** * lambda语法 */ public class LambdaExpression { public static void main(String[] args) { Comparator<Apple> colorComparator = new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return o1.getColor().compareTo(o2.getColor()); } }; List<Apple> apples = Arrays.asList(new Apple("a", 18), new Apple("c", 20), new Apple("b", 10)); for (Apple a : apples) { System.out.println(a.toString()); } System.out.println("================================="); apples.sort(colorComparator); for (Apple a : apples) { System.out.println(a.toString()); } System.out.println("================================="); //lambda expression //方法推导:接口有返回值时,注意lambda有大括号{},必须要有return,没有可以不用使用return关键词 //1、有{},必须使用return Comparator<Apple> weightComparator = (o1, o2) -> { return o1.getWeight().compareTo(o2.getWeight()); }; //2、不使用{},没有return Comparator<Apple> weightComparator2 = (o1, o2) -> o1.getWeight().compareTo(o2.getWeight()); apples.sort(weightComparator); for (Apple a : apples) { System.out.println(a.toString()); } //合法lambda表达式格式1 Function<String, Integer> stringIntegerFunction = s -> s.length(); //合法lambda表达式格式2 Predicate<Apple> great = (Apple apple) -> apple.getColor().equals("great"); Predicate<Apple> great2 = apple -> apple.getColor().equals("great"); //合法lambda表达式格式3 // (int x, int y) -> { // System.out.println(x); // System.out.println(y); // }; //合法lambda表达式格式4 Callable<Integer> integerCallable = () -> 12; //合法lambda表达式格式5 Runnable runnable = () -> { }; //合法lambda表达式格式6 Callable<String> stringCallable = () -> "hello"; //合法lambda表达式格式7 Function<String, String> stringStringFunction = (String str) -> { return "hello"; }; //合法lambda表达式格式8 Function<String, String> stringStringFunction1 = (String str) -> "hello"; } }五、学习目标熟悉lambda语法后,主要学习:function、stream。java.util.function、java.util.stream包下接口用法六、Function学习java.util.function包下主要的4中lambda接口用法以及扩展用户1、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);范例: //Funcation有返回参数类型 //1、返回Boolean类型 Function<Apple, Boolean> boolearnFunction = apple -> apple.getColor().equals("red"); //2、返回String类型 Function<Apple, String> stringFunction = apple -> apple.getColor(); //3、返回Integer类型 Function<Apple, Integer> integerFunction = apple -> apple.getWeight(); //4、。。。等等其它类型同理2、无返回值@FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t);范例: //Consumer无参数返回类型 Consumer<Apple> appleConsumer = apple -> System.out.println(apple.getColor()); Consumer<Apple> appleConsumer2 = apple -> System.out.println("hello");3、返回Boolean类型@FunctionalInterface public interface Predicate<T> { /** * 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);范例: //Predicate返回Boolean类型(判断类型) Predicate<Apple> colorPredicate = apple -> apple.getColor().equals("red"); Predicate<Apple> weightPredicate = apple -> apple.getWeight()==4;4、获取对象@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }get(); } 范例: //Supplier获取对象 Supplier<Apple> appleSupplier = Apple::new;根据上面3种接口,返回不同参数类型,在不同地方选择使用。七、那些是FunctionInterface(函数式接口)1、除了default、static的方法外,只有一个方法的接口,就是funcationInteface @FunctionalInterface interface Adder{ int add(int a, int b); }2、没有方法,但继承了有一个方法的接口是funcationInterface @FunctionalInterface interface Empty extends Adder{ }不是函数式接口的1、继承后不止一个方法,因此不是funcationInterface interface SmartAdder extends Adder{ int add(Long a, Long b); }2、没有任何方法的接口,不是funcationInterface interface DoNothing{ }
2022年09月05日
141 阅读
0 评论
2 点赞