自我成长 - lambda
type: channel
link: https://yanxizhu.com/index.php/tag/lambda/
items: JAVA8-Stream 数值格式
items: JAVA8-Stream创建
items: JAVA8-Stream源码
items: JAVA8方法推导
items: Java8-functionInterface
items: Java8-Lambda语法

JAVA8-Stream 数值格式
type: item
date: 2022-09-08T14:03:00+00:00
description: Stream数据类型1、mapToInt、mapToLong、mapToDouble可以将包装类拆箱成基本数据类型，节约内存空间范例：求和方式一：reduce实现 //方式一：reduce实现 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,6,5,4,3,2,1); list.stream().reduce(Integer::sum).ifPresent(System.out::println); 方式二：mapToInt //方式二：mapToInt list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,6,5,4,3,2,1); IntStream mapToInt = list.stream().mapToInt(i -> i.intValue()); int sum = mapToInt.sum(); System.out.println(sum);方式三：mapToInt后用reduce实现 //方式三：mapToInt后用reduce实现 list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,6,5,4,3,2,1); IntStream intStream = list.stream().mapToInt(i -> i.intValue()); int reduce = list.stream().mapToInt(i -> i.intValue()).reduce(0, (i, j) -> i + j); System.out.println(reduce);区别：直接使用reduce实现，使用的是包装类Integer，用mapToInt则可以转成int计算，占用内存更小。2、mapToObj可以将数据直接转成对象，代码量少很多。范例：需求：1--100，中满足勾股定律的数字 3\4\5 9,并返回成一个数组。1、原始分步骤写法： int a = 9; //创建1-100的数字 IntStream rangeClosed = IntStream.rangeClosed(1, 100); //找到满足勾股定律的数字 Stream<Integer> boxed = rangeClosed.filter(i -> Math.sqrt(a * a + i * i) % 1 == 0).boxed(); //将数字转变成int数组返回 Stream<int[]> stream = boxed.map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}); //输出数组数据 stream.forEach(array->System.out.println("a="+array[0]+",b="+array[1]+",c="+array[2]));2、原始写法，代码简化后 int a = 9; IntStream.rangeClosed(1, 100) .filter(i->Math.sqrt(a*a + i*i)%1==0) .boxed() .map(b->new int[]{a,b,(int)Math.sqrt(a*a+b*b)}) .forEach(array->System.out.println("a="+array[0]+",b="+array[1]+",c="+array[2]));3、mapToObj实现 int a = 9; IntStream.rangeClosed(1, 100) .filter(i->Math.sqrt(a*a + i*i)%1==0) .mapToObj(b->new int[]{a,b,(int)Math.sqrt(a*a+b*b)}) .forEach(array->System.out.println("a="+array[0]+",b="+array[1]+",c="+array[2]));输出结果：a=9,b=12,c=15 a=9,b=40,c=41使用mapToObj，代码更简洁，直接将满足条件数据，转成一个数组对象。

JAVA8-Stream创建
type: item
date: 2022-09-07T03:29:00+00:00
description: 创建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进行开发了。

JAVA8-Stream源码
type: item
date: 2022-09-06T15:03:00+00:00
description: 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,…

JAVA8方法推导
type: item
date: 2022-09-06T05:41:00+00:00
description: 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.print…

Java8-functionInterface
type: item
date: 2022-09-05T16:13:00+00:00
description: 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) { S…

Java8-Lambda语法
type: item
date: 2022-09-05T13:18:00+00:00
description: 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…