package stream;import java.util.*;import java.util.stream.*;/*** @Description* @Author msli* @Date 2021年08月17日*/public class StreamDemo {public static void main(String[] args) {// constructStreamDemo();streamOps();// ArrayList<Integer> nums = new ArrayList<>();// nums.add(1);// nums.add(12);// nums.add(48);// nums.add(7);// nums.add(25);// List<Integer> integers = nums.subList(0, 3);// Integer[] integers1 = integers.toArray(new Integer[0]);// System.out.println(Arrays.toString(integers1));/*** 在使用 java.util.stream.Collectors 类的 toMap()方法转为 Map 集合时,一定要使* 用含有参数类型为 BinaryOperator,参数名为 mergeFunction 的方法,否则当出现相同 key* 值时会抛出 IllegalStateException 异常*/// List<Pair> pairs = new ArrayList<>();// pairs.add(new Pair("version", 12.10));// pairs.add(new Pair("version", 12.19));// pairs.add(new Pair("version", 6.28));// final Map<String, Double> collect = pairs.stream().collect(Collectors.toMap(Pair::getE1, Pair::getE2, (v1, v2) -> v2));// System.out.println("collect = " + collect.toString());// // 反例// String[] departments = new String[] {"iERP", "iERP", "EIBU"};// // 抛出 IllegalStateException 异常//// Map<Integer, String> map = Arrays.stream(departments)//// .collect(Collectors.toMap(String::hashCode, str -> str));//// System.out.println("map = " + map.toString());// // 在使用 java.util.stream.Collectors 类的 toMap()方法转为 Map 集合时,一定要注// // 意当 value 为 null 时会抛 NPE 异常。// List<Pair> pairList = new ArrayList<>();// pairList.add(new Pair("version", 12.10));// pairList.add(new Pair("version", 12.19));// pairList.add(new Pair("version", null));// final Map<String, Double> map1 = pairList.stream().collect(Collectors.toMap(Pair::getE1, entry -> Optional.ofNullable(entry.getE2()).orElse(0D), (v1, v2) -> v2));// System.out.println("map1 = " + map1.toString());}static class Pair {private String e1;private Double e2;public Pair(String e1, Double e2) {this.e1 = e1;this.e2 = e2;}public String getE1() {return e1;}public void setE1(String e1) {this.e1 = e1;}public Double getE2() {return e2;}public void setE2(Double e2) {this.e2 = e2;}}/*** 流的操作* 分类:* 1. Intermediate 操作* map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered* 一个流可以后面跟随零个或多个intermediate操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。* 这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历* 2. Terminal 操作* forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator* 一个流只能有一个terminal操作,当这个操作执行后,流就被使用"光"了,无法再被操作。* 所以,这必定是流的最后一个操作。Terminal操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个side effect* 3. Short-circuiting 操作* anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit* 对于一个intermediate操作,如果它接受的是一个无限大(infinite/unbounded)的Stream,但返回一个有限的新Stream;* 对于一个terminal操作,如果它接受的是一个无限大的Stream,但能在有限的时间计算出结果。* 当操作一个无限大的 Stream,而又希望在有限时间内完成操作,则在管道内拥有一个short-circuiting操作是必要非充分条件*/public static void streamOps() {/*** map/flatMap* intermediate 操作* 作用:把 inputStream 的每个元素映射成 outputStream 的另外一个元素* 特点:map 生成的是个1:1映射,每个输入元素都按照规则转换成为另外一个元素* flatMap 是一对多映射关系*/List<Integer> nums = Arrays.asList(1, 2, 3, 4);List<Integer> squareList = nums.stream().map(n -> n * n).collect(Collectors.toList());String squareListStr = squareList.stream().map(String::valueOf).collect(Collectors.joining(","));System.out.println(squareListStr);Stream<List<Integer>> stream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6));System.out.println(stream.map(String::valueOf).collect(Collectors.joining(",")));stream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6));List<Integer> flatMapList = stream.flatMap(Collection::stream).collect(Collectors.toList());System.out.println(flatMapList.stream().map(String::valueOf).collect(Collectors.joining(",")));/*** filter 过滤筛选* intermediate 操作* 作用:filter对原始Stream进行某项测试,通过测试的元素被留下来生成一个新Stream* 留下偶数*/Integer[] sixNums = {1, 2, 3, 4, 5, 6};Integer[] evens = Stream.of(sixNums).filter(n -> n % 2 == 0).toArray(Integer[]::new);System.out.println(Arrays.toString(evens));/*** forEach* terminal 操作* 作用:forEach方法接收一个Lambda表达式,然后在Stream的每一个元素上执行该表达式* 多核系统优化时,可以parallelStream().forEach(),只是此时原有元素的次序没法保证,并行的情况下将改变串行时操作的行为,此时forEach本身的实现不需要调整* forEach是terminal操作, 执行后,Stream 的元素就被"消费"掉了,你无法对一个Stream进行两次terminal运算* forEach 不能修改自己包含的本地变量值,也不能用break/return之类的关键字提前结束循环。*/Integer[] nums2 = {1, 2, 3, 4, 5, 6, 84};Stream.of(nums2).filter(n -> n > 3).forEach(System.out::println);/*** peek* intermediate 操作* 与 forEach 功能类型*/List<String> list = Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3).peek(e -> System.out.println("Filtered value: " + e)).map(String::toUpperCase).peek(e -> System.out.println("Mapped value: " + e)).collect(Collectors.toList());/*** findFirst* termimal兼short-circuiting操作* 返回Stream的第一个元素或者空* 它的返回值类型Optional:这也是一个模仿 Scala 语言中的概念,作为一个容器,它可能含有某值,或者不包含,使用它的目的是尽可能避免NullPointerException* 类似的:findAny、max/min、reduce等方法等返回Optional值*/Optional<String> firstStr = Stream.of("one", "two", "tt", "tt23").filter(element -> element.contains("tt")).findFirst();System.out.println("findFirstStr: " + firstStr.get());/*** reduce* termimal兼short-circuiting操作* 把Stream元素组合起来* 提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面Stream的第一个、第二个、第n个元素组合;* 从这个意义上说,字符串拼接、数值的 sum、min、max、average都是特殊的reduce*/// 求和,sumValue = 1 + 1+2+3+4 = 11 , 有起始值// reduceStream.reduce(0, (a, b) -> a+b);int sumValue = Stream.of(1, 2, 3, 4).reduce(1, Integer::sum);System.out.println("reduce 求和 有起始值 " + sumValue);// 求和,sumValue = 10, 无起始值sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();System.out.println("reduce 求和 无起始值 " + sumValue);// 字符串连接,concat = "ABCD"String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);System.out.println("reduce 字符串连接 " + concat);String concat1 = Stream.of("A", "B", "C", "D").reduce(";", String::concat);System.out.println("reduce 字符串连接 " + concat1);// 求最小值,minValue = -3.0double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);System.out.println("reduce 求最小值 " + minValue);// 过滤,字符串连接,concat = "ace"concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);System.out.println("reduce 过滤+字符串连接 " + concat);/*** limit / skip* intermediate 操作* limit返回Stream的前面n个元素* skip则是扔掉前n个元素(它是由一个叫 subStream的方法改名而来)*/int[] ints = IntStream.rangeClosed(1, 100).limit(20).skip(10).toArray();System.out.println(Arrays.toString(ints));}/*** 流转为其他数据结构 demo*/public static void typeConvert() {Stream<String> stream = Stream.of("a", "c", "regfgfdfd");// 1. to arrayString[] array = stream.toArray(String[]::new);// 2. to collectList<String> list1 = stream.collect(Collectors.toList());ArrayList<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));HashSet<String> sets = stream.collect(Collectors.toCollection(HashSet::new));Stack<String> stack = stream.collect(Collectors.toCollection(Stack::new));// 3. StringString str = stream.collect(Collectors.joining(", ", "[", "]"));}/*** 不同方式的流构造类型*/public static void constructStreamDemo() {// 1. 单个元素Stream stream = Stream.of("a", "b", "c");System.out.println("individualStream");stream.forEach(System.out::println);// 2. 数组String[] strArr = new String[]{"a", "b", "c"};Stream<String> stream1 = Stream.of(strArr);Stream<String> stream2 = Arrays.stream(strArr);// 基本数值类型数组 IntStream LongStream DoubleStreamint[] ints = new int[]{1, 23, 32};IntStream intStream = IntStream.of(ints);intStream = Arrays.stream(ints);System.out.println("intStream");intStream.forEach(System.out::println);IntStream.rangeClosed(1, 444).forEach(item -> System.out.print(item + " "));System.out.println();double[] doubles = {3.4, 232, 90};DoubleStream doubleStream = DoubleStream.of(doubles);doubleStream = Arrays.stream(doubles);System.out.println("doubleStream");doubleStream.forEach(System.out::println);long[] longs = {2L, 4343434L, 232L};LongStream longStream = LongStream.of(longs);longStream = Arrays.stream(longs);System.out.println("longStream");longStream.forEach(System.out::println);// 3. 集合List<String> stringList = Arrays.asList(strArr);Stream<String> stream3 = stringList.stream();System.out.println("collectStream");stream3.forEach(System.out::println);}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。