Java8InAction_Chapter05

  1 import static java.util.stream.Collectors.toList;
  2 
  3 import java.io.IOException;
  4 import java.util.Arrays;
  5 import java.util.List;
  6 import java.util.function.IntSupplier;
  7 import java.util.stream.IntStream;
  8 import java.util.stream.Stream;
  9 
 10 /**
 11  * 在这里编写类的功能描述
 12  *
 13  * @author shangjinyu
 14  * @created 2017/10/4
 15  */
 16 public class Notes {
 17     //使用流
 18     //过滤:filter() 去重:distinct() 取前几:limit() 去掉前几:skip() 转换:map() 转换合并:flatMap()
 19     //查找:anyMatch(), allMatch(), noneMatch(), findAny(), findFirst()
 20     /**
 21      * 操作         类型           返回类型            使用的类型/函数式接口             函数描述符
 22      * filter       中间           Stream<T>          Predicate<T>                    T -> boolean
 23      * distinct     中间           Stream<T>
 24      * skip         中间           Stream<T>          long
 25      * limit        中间           Stream<T>          long
 26      * map          中间           Stream<R>          Function<T,R>                   T -> R
 27      * flatMap      中间           Stream<R>          Function<T, Stream<R>>          T -> Stream<R>
 28      * sorted       中间           Stream<T>          Comparator<T>                   (T, T) -> int
 29      * anyMatch     终端           boolean            Predicate<T>                    T -> boolean
 30      * noneMatch    终端           boolean            Predicate<T>                    T -> boolean
 31      * allMatch     终端           boolean            Predicate<T>                    T -> boolean
 32      * findAny      终端           Optional<T>
 33      * findFirst    终端           Optional<T>
 34      * forEach      终端           void               Consumer<T>                     T -> void
 35      * collect      终端           R                  Collector<T,A,R>
 36      * reduce       终端           Optional<T>        BinaryOperator<T>               (T,T) -> T
 37      * count        终端           long
 38      */
 39     public static void main(String...args) throws IOException {
 40         //获取"Goodbye", "World" 中出现的字母
 41         String[] arrayOfWords = {"Goodbye", "World"};
 42         Arrays.stream(arrayOfWords)
 43                 .flatMap((String line) -> Arrays.stream(line.split("")))
 44                 .distinct()
 45                 .forEach(System.out::println);
 46 
 47         //选出number1和number2中元素组成的所有数对中可以被3整除的数对
 48         List<Integer> numbers1 = Arrays.asList(1,2,3,4,5);
 49         List<Integer> numbers2 = Arrays.asList(6,7,8);
 50         List<int[]> pairs1 =
 51                 numbers1.stream()
 52                         .flatMap(i -> numbers2.stream()
 53                                 .map(j -> new int[]{i, j})
 54                         )
 55                         .filter(pair -> (pair[0] + pair[1]) % 3 == 0)
 56                         .collect(toList());
 57         List<int[]> pairs2 =
 58                 numbers1.stream()
 59                         .flatMap(i -> numbers2.stream()
 60                                 .filter(j -> (i + j) % 3 == 0)
 61                                 .map(j -> new int[]{i, j})
 62                         )
 63                         .collect(toList());
 64         pairs1.forEach(pair -> System.out.println("(" + pair[0] + ", " + pair[1] + ")"));
 65         /**
 66          *  流的构建方式
 67          */
 68         // Stream.of
 69         Stream<String> stream = Stream.of("Java 8", "Lambdas", "In", "Action");
 70         stream.map(String::toUpperCase).forEach(System.out::println);
 71 
 72         // Stream.empty
 73         Stream<String> emptyStream = Stream.empty();
 74 
 75         // Arrays.stream
 76         int[] numbers = {2, 3, 5, 7, 11, 13};
 77         System.out.println(Arrays.stream(numbers).sum());
 78 
 79         // fibonnaci with iterate
 80         Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1],t[0] + t[1]})
 81                 .limit(10)
 82                 .forEach(t -> System.out.println("(" + t[0] + ", " + t[1] + ")"));
 83 
 84         // random stream of doubles with Stream.generate
 85         Stream.generate(Math::random)
 86                 .limit(10)
 87                 .forEach(System.out::println);
 88 
 89         IntSupplier fib = new IntSupplier(){
 90             private int previous = 0;
 91             private int current = 1;
 92             public int getAsInt(){
 93                 int nextValue = this.previous + this.current;
 94                 this.previous = this.current;
 95                 this.current = nextValue;
 96                 return this.previous;
 97             }
 98         };
 99         IntStream.generate(fib).limit(10).forEach(System.out::println);
100 
101         //数值流
102         Stream<int[]> pythagoreanTriples =
103                 IntStream.rangeClosed(1, 100).boxed()
104                         .flatMap(a -> IntStream.rangeClosed(a, 100)
105                                 .filter(b -> Math.sqrt(a*a + b*b) % 1 == 0).boxed()
106                                 .map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}));
107     }
108 }
原文地址:https://www.cnblogs.com/3013218061shang/p/7628087.html