Stream流的创建方法
public static void main(String[] args) { Stream stream1 = Stream.of("hello","world","hello stream"); String[] myArray = new String[]{"hello","world","hello stream"}; Stream stream2 = Arrays.stream(myArray); Stream stream3 = Stream.of(myArray); List<String> list = Arrays.asList(myArray); Stream stream4 = list.stream(); stream1.forEach(System.out::println); stream2.forEach(System.out::println); stream3.forEach(System.out::println); stream4.forEach(System.out::println); }
Stream的基础使用:
public static void main(String[] args) { IntStream.range(1,10).forEach(System.out::println); //我来算一算 1+...+100 等于多少 IntStream.rangeClosed(1,100).reduce(Integer::sum).ifPresent(System.out::print); }
函数式编程传递的是一种行为,根据传递的行为处理数据
public static void main(String[] args) { Stream<java.lang.String> stream = Stream.of("hello","world","hello stream"); String[] list = stream.toArray(length -> new String[length]); for (int i = 0 ;i<list.length;i++){ System.out.println(list[i]); } }
<A> A[] toArray(IntFunction<A[]> generator);方法接收一个IntFunction<A[]>类型函数式接口,在IntFunction<A[]>中接收一个int 返回一个R 也就是返回A[],文档中有说明,【The generator function takes an integer, which is the size of the desired array 】这个int值就是这个流中array的size。
所以这个lambada表达式是:
String[] list = stream.toArray(length -> new String[length]);
看到new Stirng[length],我们明显可以使用构造方法引用:
String[] list2 = stream.toArray(String[]::new);
public static void main(String[] args) { Stream<java.lang.String> stream = Stream.of("hello","world","hello stream"); // String[] list = stream.toArray(length -> new String[length]); // for (int i = 0 ;i<list.length;i++){ // System.out.println(list[i]); // } //等价于: String[] list2 = stream.toArray(String[]::new); for (int i = 0 ;i < list2.length;i++){ System.out.println(list2[i]); } }