自我成长 - stream
type: channel
link: https://www.yanxizhu.com/index.php/tag/stream/
items: JAVA8-Stream parallel 并行执行
items: JAVA8-Stram练手
items: JAVA8-Stream 数值格式
items: JAVA8-Stream API
items: JAVA8-Stream创建
items: JAVA8-Stream源码

JAVA8-Stream parallel 并行执行
type: item
date: 2022-09-19T15:50:00+00:00
description: Stream parallel 并行执行范例：求1~100000000的和，执行10次，看时间效率。代码package com.example.study.java8.collector; import java.util.function.Function; import java.util.stream.LongStream; import java.util.stream.Stream; /** * Stream parallel并行执行 * 实列：求10次，1~100000000的和，看时间效率。 */ public class ParallelProcessing { public static void main(String[] args) { //获取电脑CPU核数 System.out.println("当前电脑CPU核数= " + Runtime.getRuntime().availableProcessors()); System.out.println("The best process time(normalAdd)=> " + measureSumPerformance(ParallelProcessing::normalAdd, 100_000_000) + " MS"); System.out.println("The best process time(iterateStream1)=> " + measureSumPerformance(ParallelProcessing::iterateStream1, 100_000_000) + " MS"); System.out.println("The best process time(iterateStream2)=> " + measureSumPerformance(ParallelProcessing::iterateStream2, 100_000_000) + " MS"); System.out.println("The best process time(iterateStream3)=> " + measureSumPerformance(ParallelProcessing::iterateStream3, 100_000_000) + " MS"); System.out.println("The best process time(iterateStream4)=> " + measureSumPerformance(ParallelProcessing::iterateStream4, 100_000_000) + " MS"); System.out.println("The best process time(iterateStream5)=> " + measureSumPerformance(ParallelProcessing::iterateStream5, 100_000_000) + " MS"); } private static long measureSumPerformance(Function<Long, Long> adder, long limist) { long fastest = Long.MAX_VALUE; for (int i = 0; i < 10; i++) { Long startTimestamp = System.currentTimeMillis(); long result = adder.apply(limist); long duration = System.currentTimeMillis() - startTimestamp; // System.out.println("The result of sum=>"+result); if (duration < fastest) fastest = duration; } return fastest; } /** * 1、函数式编程实现：没有使用并行执行 * * @param limit * @return */ public static long iterateStream1(long limit) { return Stream.iterate(1L, i -> i + 1).limit(limit).reduce(0L, Long::sum); } /** * 2、函数式编程实现-进化：使用并行执行，要进行拆箱装箱 * * @param limit * @return */ public static long iterateStream2(long limit) { return Stre…

JAVA8-Stram练手
type: item
date: 2022-09-11T07:25:40+00:00
description: JAVA8-Stram练手交易员对象：package com.example.study.java8.streams.demo; /** * 交易员 */ public class Trader { private final String name; private final String city; public Trader(String n, String c){ this.name = n; this.city = c; } public String getName(){ return this.name; } public String getCity(){ return this.city; } public String toString(){ return "Trader:"+this.name + " in " + this.city; } } 交易对象package com.example.study.java8.streams.demo; /** * 交易 */ public class Transaction { private final Trader trader; private final int year; private final int value; public Transaction(Trader trader, int year, int value){ this.trader = trader; this.year = year; this.value = value; } public Trader getTrader(){ return this.trader; } public int getYear(){ return this.year; } public int getValue(){ return this.value; } public String toString(){ return "{" + this.trader + ", " + "year: "+this.year+", " + "value:" + this.value +"}"; } } 需求说明：1、交易年未2011年，并按交易金额排序2、获取城市并去重3、获取交易员所在城市为“Cambridge”的交易员，去重，并按交易员名字排序4、获取所有交易员名字，并排序,拼接成字符串5、交易员城市是否有在Milan的6、打印所有交易值，且交易员所在城市是Milan的7、找最大的值8、找最小的值需求实现范例：package com.example.study.java8.streams.demo; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /** * 交易员进行交易 */ public class StreamInAction { public static void main(String[] args) { Trader raoul = new Trader("Raoul", "Cambridge"); Trader mario = new Trader("Mario", "Milan"); Trader alan = new Trader("Alan", "Cambridge"); Trader brian = new Trader("Brian", "Cambridge"); List<Transaction> transactions = Arrays.asList( new Transaction(brian, 2011, 300), new Transaction(raoul, 2012, 1000), new Transaction(raoul, 2011, 400), new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700), new Transaction(alan, 2012, 950) ); //1、交易年未2011年，并按交易金额排序 transactions.stream() .filter(t -> t.getYear() == 2011) .sorted(Comparator.comparing(Transaction::getValue)) .collect(toList()) .forEach(System.out::pri…

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 API
type: item
date: 2022-09-07T09:39:00+00:00
description: 二、Stream API：filter、distinct、skip、limit被操作数据List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,6,5,4,3,2,1);1、filter 过滤范例：//filter 过滤 List<Integer> filterResult = list.stream().filter(i -> i % 2 == 0).collect(toList()); filterResult.stream().forEach(System.out::println);2、distinct 去重范例： //distinct 去重 List<Integer> distinctResult = list.stream().distinct().collect(toList()); distinctResult.stream().forEach(System.out::println);3、skip 截断范例： //skip 截断(跳过前面几个,超过长度，直接返回空) List<Integer> skipResult = list.stream().skip(5).collect(toList()); skipResult.stream().forEach(System.out::println);4、limit 查询几条范例： //limit 查询几条 List<Integer> limitResult = list.stream().limit(3).collect(toList()); limitResult.stream().forEach(System.out::println);二、Stream API：Map1、map 数据处理被操作数据List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,6,5,4,3,2,1); 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)); String[] arrays = {"Hello","world"};范例1： //1、map List<Integer> mapResult = list.stream().map(i -> i * 2).collect(toList()); mapResult.stream().forEach(System.out::println);范例2： //2、map menu.stream().map(Dish::getName).forEach(System.out::println);范例3：//3、flatMap 扁平化 //拆分成String[]: {h,e,l,l,o}，{w,o,r,l,d} Stream<String[]> splitStream = Arrays.stream(arrays).map(s -> s.split("")); //flatMap扁平化，将{h,e,l,l,o}，{w,o,r,l,d}每个数组转成Stream<String> Stream<String> stringStream = splitStream.flatMap(Arrays::stream); stringStream.distinct().forEach(System.out::println);打印结果：H e l o w r d三、Stream API：Match1、Match匹配范例：1.1、allMatch 全部满足条件 Stream<Integer> list = Arrays.stream(n…

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,…