JDK8.0 流stream 基本操作

xiaoxiao2021-02-28  89

Stream当成一个高级版本的Iterator。原始版本的Iterator,用户只能一个一个的遍历元素并对其执行某些操作;高级版本的Stream,用户只要给出需要对其包含的元素执行什么操作,比如“过滤掉长度大于10的字符串”、“获取每个字符串的首字母”等,具体这些操作如何应用到每个元素上 一.初始化 1.value Stream<String> stream = Stream. of ( "a" , "b" , "c" ); 2.array String [] strArray = new String[] { "a" , "b" , "c" }; stream = Stream. of (strArray); stream = Arrays. stream (strArray); 3.list List<String> list = Arrays. asList (strArray); stream = list.stream(); 二.流转换 1.转array String[] strArray1 = stream.toArray(String[]::new); 2.转list List <String> list = stream.collect(Collectors. toList ()); 3.转String String str = stream.collect(Collectors. joining ()).toString(); 三.操作(创建stream-->转换stream-->聚合) 1.map List<String> list = stream.map(String ::toUpperCase). collect(Collectors. toList ()); 2.filter String a = stream.filter(l->l.equals( "a" )). collect(Collectors. joining ()); 3.forEach stream.forEach(System. out ::println); personList2 .forEach(a->System. out .println(a.getName())); 4.peek对每个元素操作 Stream. of ( "one" , "two" , "three" , "four" ) .peek(e -> System. out .println( "Filtered value: " + e)) .map(String::toUpperCase) .peek(e -> System. out .println( "Mapped value: " + e)) .collect(Collectors. toList ()); 5.reduce: 主要作用是把 Stream 元素组合起来 // 求最小值, minValue = -3.0 double minValue = Stream. of (- 1.5 , 1.0 , - 3.0 , - 2.0 ).reduce(Double. MAX_VALUE , Double:: min ); // 求和, sumValue = 10, 有起始值 int sumValue = Stream. of ( 1 , 2 , 3 , 4 ).reduce( 0 , Integer:: sum ); 6. limit/skip limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素 7.sorted List<Person> personList2 = list.stream().limit( 2 ).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors. toList ()); personList2.forEach(a->System. out .println(a.getName())); 其他操作 map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
转载请注明原文地址: https://www.6miu.com/read-75461.html

最新回复(0)