java.util.stream.Stream 小咪咪 2023-07-17 14:17 13阅读 0赞 > [https://blog.csdn.net/qq\_40794973/article/details/86882454\#t32][https_blog.csdn.net_qq_40794973_article_details_86882454_t32] -------------------- # 2 案例数据来源 # @Data public class Employee { /**主键*/ private Integer id; /**姓名*/ private String name; /**年龄*/ private Integer age; /**薪水*/ private Double salary; /**用户状态*/ private Status status; public enum Status { //空闲 FREE, //忙碌 BUSY, // VOCATION; } public Employee(Integer id, String name, Integer age, Double salary, Status status) { this.id = id; this.name = name; this.age = age; this.salary = salary; this.status = status; } } public class StreamDemo { List<Employee> emps; @Before public void before() { emps= Arrays.asList( new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE), new Employee(102, "李四", 59, 6666.66, Employee.Status.BUSY), new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION), new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY), new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE), new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE), new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY) ); } -------------------- # 3 创建Stream的四种方式 # ## 3.1 通过集合 ## Java8中的Collection接口被扩展,提供了两个获取流的方法; //java.util.Collection#stream default Stream<E> stream() // 返回一个顺序流 //java.util.Collection#parallelStream default Stream<E> parallelStream() // 返回一个并行流 //1. Collection 提供了两个方法 stream() 与 parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); //获取一个顺序流 Stream<String> parallelStream = list.parallelStream(); //获取一个并行流 -------------------- ## 3.2 通过数组 ## Java8中的Arrays的静态方法stream()可以获取数组流 //java.util.Arrays#stream(T[]) public static <T> Stream<T> stream(T[] array)// 返回一个流 重载形式:能够处理对应基本类型的数组 public static IntStream stream(int[] array) public static LongStream stream(long[] array) public static DoubleStream stream(double[] array) //2. 通过 Arrays 中的 stream() 获取一个数组流 Integer[] nums = new Integer[10]; Stream<Integer> stream1 = Arrays.stream(nums); -------------------- ## 3.3 通过Stream的of() ## 可以使用静态方法Stream.of();通过显示值创建一个流,它可以接收任意数量的参数 //java.util.stream.Stream#of(T...) public static<T> Stream<T> of(T... values) // 返回一个流 //3. 通过 Stream 类中静态方法 of() Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6); ## **3.4 **由函数创建流 ## 可以使用静态方法Stream.iterate() 和 Stream.generate()创建无限流 //迭代 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) //生成 public static<T> Stream<T> generate(Supplier<T> s) //4. 创建无限流 //迭代 Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10); stream3.forEach(System.out::println); //生成 Stream<Double> stream4 = Stream.generate(Math::random).limit(2); stream4.forEach(System.out::println); > Iterable转成Stream:[https://www.baeldung.com/java-iterable-to-stream][https_www.baeldung.com_java-iterable-to-stream] > > Iterable接口没又提供转换到stream方法,我们可以用*StreamSupport.stream()* 来实现 > > [https://docs.oracle.com/javase/8/docs/api/java/util/stream/StreamSupport.html][https_docs.oracle.com_javase_8_docs_api_java_util_stream_StreamSupport.html] Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream"); Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false); -------------------- # 4 Stream的中间操作 # 多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则**中间操作不会执行任何的处理**! 而在终止操作时一次性全部处理,称为 “惰性求值” ## **4.1 **筛选与切片 ## <table> <tbody> <tr> <td> <p><strong>方 法</strong></p> </td> <td> <p><strong>描 述</strong></p> </td> </tr> <tr> <td> <p><strong>filter(Predicate</strong><strong> p</strong><strong>)</strong></p> </td> <td> <p>接收 Lambda , 从流中排除某些元素</p> </td> </tr> <tr> <td> <p><strong>distinct()</strong></p> </td> <td> <p>筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素</p> </td> </tr> <tr> <td> <p><strong>limit(</strong><strong>long maxSize</strong><strong>)</strong></p> </td> <td> <p>截断流,使其元素不超过给定数量</p> </td> </tr> <tr> <td> <p><strong>skip(</strong><strong>long n</strong><strong>)</strong></p> </td> <td> <p>跳过元素,返回一个扔掉了前 n 个元素的流;若流中元素不足 n 个,则返回一个空流;与 limit(n) 互补</p> </td> </tr> </tbody> </table> //内部迭代:迭代操作 Stream API 内部完成 @Test public void testLazy() { //所有的中间操作不会做任何的处理 Stream<Employee> stream = emps.stream() .filter((e) -> { System.out.println("测试中间操作"); return e.getAge() <= 35; }); //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为 “惰性求值” stream.forEach(System.out::println); //注释 前面打印不会输出 } //外部迭代 @Test public void testExternal() { Iterator<Employee> it = emps.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } @Test public void testShortCircuit() { emps.stream() .filter((e) -> { System.out.println("短路!"); // && || return e.getSalary() >= 5000; }).limit(3)//找到了 3 条 后面的就不在去找了 .forEach(System.out::println); } @Test public void testSkip() { emps.parallelStream() .filter((e) -> e.getSalary() >= 5000) .skip(2) .forEach(System.out::println); } // distinct 需要重写Employee的hashCode()和equals() @Test public void testDistinct() { emps.stream() .distinct() .forEach(System.out::println); } ## 4.2 映 射 ## <table> <tbody> <tr> <td> <p><strong>方法</strong></p> </td> <td> <p><strong>描述</strong></p> </td> </tr> <tr> <td> <p><strong>map(Function</strong><strong> f</strong><strong>)</strong></p> </td> <td> <p>接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素</p> </td> </tr> <tr> <td> <p><strong>mapToDouble(ToDoubleFunction f)</strong></p> </td> <td> <p>接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream</p> </td> </tr> <tr> <td> <p><strong>mapToInt(ToIntFunction f)</strong></p> </td> <td> <p>接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream</p> </td> </tr> <tr> <td> <p><strong>mapToLong(ToLongFunction f)</strong></p> </td> <td> <p>接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream</p> </td> </tr> <tr> <td> <p><strong>flatMap(Function f)</strong></p> </td> <td> <p>接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流</p> </td> </tr> </tbody> </table> // 2. 中间操作 // 映射 // map: 接收 Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 // flatMap: 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流理解为 Collection的add和addAll 的关系 Stream<String> str = emps.stream() .map((e) -> e.getName()); @Test public void test(){ List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); Stream<String> stream = strList.stream() .map(String::toUpperCase); stream.forEach(System.out::println); } //StreamDemo //StreamDemo里面的静态方法 public static Stream<Character> filterCharacter(String str) { List<Character> list = new ArrayList<>(); for (Character ch : str.toCharArray()) { list.add(ch); } return list.stream(); } @Test public void test() { List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); Stream<Stream<Character>> stream = strList.stream() .map(StreamDemo::filterCharacter); stream.forEach((item) -> { item.forEach(System.out::println); }); } @Test public void test() { List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); Stream<Character> stream = strList.stream() .flatMap(StreamDemo::filterCharacter); stream.forEach(System.out::println); } -------------------- ## 4.3 排序 ## <table> <thead> <tr> <th> <p><strong>方法</strong></p> </th> <th> <p><strong>描述</strong></p> </th> </tr> </thead> <tbody> <tr> <td> <p><strong>sorted()</strong></p> </td> <td> <p>产生一个新流,其中按自然顺序排序</p> </td> </tr> <tr> <td> <p><strong>sorted(Comparator</strong> <strong>com)</strong></p> </td> <td> <p>产生一个新流,其中按比较器顺序排序</p> </td> </tr> </tbody> </table> @Test public void testSort() { emps.stream() .map(Employee::getSalary) .sorted() .forEach(System.out::println); } /** * 年龄降序 */ @Test public void testSort_desc_1() { emps.stream() .sorted((x, y) -> y.getAge() - x.getAge()).forEach(System.out::println); } @Test public void testSort_desc_2() { emps.stream() .sorted((x, y) -> y.getAge().compareTo(x.getAge())).forEach(System.out::println); } /** * 薪水升序 */ @Test public void testSort() { emps.stream() .sorted((x, y) -> { Double xSalary = x.getSalary(); Double ySalary = y.getSalary(); return xSalary.compareTo(ySalary); }) .forEach(System.out::println); } @Test public void testSort() { emps.stream() .sorted((x, y) -> { if (x.getAge() == y.getAge()) { return x.getName().compareTo(y.getName()); } else { return Integer.compare(x.getAge(), y.getAge()); } }).forEach(System.out::println); } -------------------- # 5 Stream 的终止操作 # 终止操作会从流的流水线生成结果,其结果可以是任何不是流的值,例如List、Integer,甚至是void;**流进行了终止操作后不能再次使用** ## 5.1 匹配与查找 ## <table> <thead> <tr> <th> <p><strong>方法</strong></p> </th> <th> <p><strong>描述</strong></p> </th> </tr> </thead> <tbody> <tr> <td> <p><strong>allMatch(</strong><strong>Predicate p</strong><strong>)</strong></p> </td> <td> <p>检查是否匹配所有元素</p> </td> </tr> <tr> <td> <p><strong>anyMatch</strong>(<strong>Predicate p</strong>)</p> </td> <td> <p>检查是否至少匹配一个元素</p> </td> </tr> <tr> <td> <p><strong>noneMatch(Predicate</strong> <strong> p)</strong></p> </td> <td> <p>检查是否没有匹配所有元素</p> </td> </tr> <tr> <td> <p><strong>findFirst()</strong></p> </td> <td> <p>返回第一个元素</p> </td> </tr> <tr> <td> <p><strong>findAny()</strong></p> </td> <td> <p>返回当前流中的任意元素</p> </td> </tr> </tbody> </table> <table> <thead> <tr> <th> <p><strong>方法</strong></p> </th> <th> <p><strong>描述</strong></p> </th> </tr> </thead> <tbody> <tr> <td> <p><strong>count()</strong></p> </td> <td> <p>返回流中元素总数</p> </td> </tr> <tr> <td> <p><strong>max(Comparator</strong><strong> c</strong><strong>)</strong></p> </td> <td> <p>返回流中最大值</p> </td> </tr> <tr> <td> <p><strong>min(Comparator</strong><strong> c</strong><strong>)</strong></p> </td> <td> <p>返回流中最小值</p> </td> </tr> <tr> <td> <p><strong>forEach(Consumer</strong><strong> c</strong><strong>)</strong></p> </td> <td> <p>内部迭代 (使用 Collection 接口需要用户去做迭代,称为外部迭代;相反Stream API 使用内部迭代它帮你把迭代做了)</p> </td> </tr> </tbody> </table> @Test public void testMatch(){ boolean allMatch = emps.stream() .allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY)); System.out.println(allMatch);//false boolean anyMatch = emps.stream() .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY)); System.out.println(anyMatch);//true boolean noneMatch = emps.stream() .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY)); System.out.println(noneMatch);//false } @Test public void testFind() { Optional<Employee> firstEmp = emps.stream() .sorted(Comparator.comparingDouble(Employee::getSalary))//(e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()) .findFirst(); firstEmp.orElse(new Employee(105, "蔡徐坤", 38, 5555.55, Employee.Status.BUSY)); //为了防止空指针异常返回的是一个Optional 如果为空就就用元素替代 System.out.println(firstEmp.get()); Optional<Employee> anyEmp = emps.parallelStream() .filter((e) -> e.getStatus().equals(Employee.Status.FREE)) .findAny(); System.out.println(anyEmp.get()); } @Test public void testCountMaxAndMin() { long count = emps.stream() .filter((e) -> e.getStatus().equals(Employee.Status.FREE)) .count(); System.out.println(count); Optional<Double> max = emps.stream() .map(Employee::getSalary) .max(Double::compare); System.out.println(max.get()); Optional<Employee> min = emps.stream() .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(min.get()); } //注意:流进行了终止操作后,不能再次使用 @Test public void testTermination() { Stream<Employee> stream = emps.stream() .filter((e) -> e.getStatus().equals(Employee.Status.FREE)); long count = stream.count(); //IllegalStateException stream.map(Employee::getSalary) .max(Double::compare); } ## **5.2 归约** ## <table> <thead> <tr> <th> <p><strong>方法</strong></p> </th> <th> <p><strong>描述</strong></p> </th> </tr> </thead> <tbody> <tr> <td> <p><strong>reduce(T iden, BinaryOperator b)</strong></p> </td> <td> <p>可以将流中元素反复结合起来,得到一个值。返回 T</p> </td> </tr> <tr> <td> <p><strong>reduce(BinaryOperator b)</strong></p> </td> <td> <p>可以将流中元素反复结合起来,得到一个值。返回 Optional<T></p> </td> </tr> </tbody> </table> > 备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它 来进行网络搜索而出名。 //返回的是Integer,应为无论如何都有个起始值,不可能为空 @Test public void testReduce() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer sum = list.stream() .reduce(0, (x, y) -> x + y); //求和 首先把0(起始值)作为x,从流中取出1作为y x+y = 1,然后把1作为x,从流中取出2作为y x+y = 3 循环往复 System.out.println(sum); } //这个是有可能为空的 @Test public void testReduce() { Optional<Double> op = emps.stream() .map(Employee::getSalary) .reduce(Double::sum); System.out.println(op.get()); } ## 5.3 收集 ## <table> <thead> <tr> <th> <p><strong>方 法</strong></p> </th> <th> <p><strong>描 述</strong></p> </th> </tr> </thead> <tbody> <tr> <td> <p>collect(Collector c)</p> </td> <td> <p>将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法</p> </td> </tr> </tbody> </table> **Collector** 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map);另外**Collectors** 实用类提供了很多静态方法,可以方便地创建常见收集器实例 <table> <thead> <tr> <th> <p>方法</p> </th> <th> <p>返回类型</p> </th> <th> <p>作用</p> </th> </tr> </thead> <tbody> <tr> <td> <p><span style="color:#f33b45;">toList</span></p> </td> <td> <p>List<T></p> </td> <td> <p>把流中元素收集到List</p> </td> </tr> <tr> <td colspan="3"> <p><u>List</u><Employee> <u>emps</u>= list.stream().collect(Collectors.toList());</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">toSet</span></p> </td> <td> <p>Set<T></p> </td> <td> <p>把流中元素收集到Set</p> </td> </tr> <tr> <td colspan="3"> <p>Set<Employee> <u>emps</u>= list.stream().collect(Collectors.toSet());</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">toCollection</span></p> </td> <td> <p>Collection<T></p> </td> <td> <p>把流中元素收集到创建的集合</p> </td> </tr> <tr> <td colspan="3"> <p>Collection<Employee> <u>emps </u>=list.stream().collect(Collectors.toCollection(ArrayList::new));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">counting</span></p> </td> <td> <p>Long</p> </td> <td> <p>计算流中元素的个数</p> </td> </tr> <tr> <td colspan="3"> <p>long <u>count</u> = list.stream().collect(Collectors.counting());</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">summingInt</span></p> </td> <td> <p>Integer</p> </td> <td> <p>对流中元素的整数属性求和</p> </td> </tr> <tr> <td colspan="3"> <p>int <u>total</u>=list.stream().collect(Collectors.summingInt(Employee::getSalary));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">averagingInt</span></p> </td> <td> <p>Double</p> </td> <td> <p>计算流中元素Integer属性的平均值</p> </td> </tr> <tr> <td colspan="3"> <p>double <u>avg </u>= list.stream().collect(Collectors.averagingInt(Employee::getSalary));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">summarizingInt</span></p> </td> <td> <p>IntSummaryStatistics</p> </td> <td> <p>收集流中Integer属性的统计值。如:平均值</p> </td> </tr> <tr> <td colspan="3"> <p>int SummaryStatistics<u>iss</u>= list.stream().collect(Collectors.summarizingInt(Employee::getSalary));</p> </td> </tr> </tbody> </table> <table> <tbody> <tr> <td> <p><span style="color:#f33b45;">joining</span></p> </td> <td> <p>String</p> </td> <td> <p>连接流中每个字符串</p> </td> </tr> <tr> <td colspan="3"> <p>String <u>str</u>= list.stream().map(Employee::getName).collect(Collectors.joining());</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">maxBy</span></p> </td> <td> <p>Optional<T></p> </td> <td> <p>根据比较器选择最大值</p> </td> </tr> <tr> <td colspan="3"> <p>Optional<Emp><u>max</u>= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">minBy</span></p> </td> <td> <p>Optional<T></p> </td> <td> <p>根据比较器选择最小值</p> </td> </tr> <tr> <td colspan="3"> <p>Optional<Emp> <u>min</u> = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">reducing</span></p> </td> <td> <p>归约产生的类型</p> </td> <td> <p>从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值</p> </td> </tr> <tr> <td colspan="3"> <p>int <u>total</u>=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">collectingAndThen</span></p> </td> <td> <p>转换函数返回的类型</p> </td> <td> <p>包裹另一个收集器,对其结果转换函数</p> </td> </tr> <tr> <td colspan="3"> <p>int <u>how</u>= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">groupingBy</span></p> </td> <td> <p>Map<K, List<T>></p> </td> <td> <p>根据某属性值对流分组,属性为K,结果为V</p> </td> </tr> <tr> <td colspan="3"> <p>Map<Emp.Status, List<Emp>> map= list.stream() .collect(Collectors.groupingBy(Employee::getStatus));</p> </td> </tr> <tr> <td> <p><span style="color:#f33b45;">partitioningBy</span></p> </td> <td> <p>Map<Boolean, List<T>></p> </td> <td> <p>根据true或false进行分区</p> </td> </tr> <tr> <td colspan="3"> <p>Map<Boolean,List<Emp>> <u>vd</u><u> </u>= list.stream().collect(Collectors.partitioningBy(Employee::getManage));</p> </td> </tr> </tbody> </table> 格式转换 //collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法 @Test public void testCollect() { List<String> empNameList = emps.stream() .map(Employee::getName) .collect(Collectors.toList()); System.out.println(String.join(" ", empNameList)); Set<String> empNameSet = emps.stream() .map(Employee::getName) .collect(Collectors.toSet()); System.out.println(String.join(" ", empNameSet)); //搜集到特殊的集合中 HashSet<String> empNameHashSet = emps.stream() .map(Employee::getName) .collect(Collectors.toCollection(HashSet::new)); System.out.println(String.join(" ", empNameHashSet)); } 统计 @Test public void test(){ Optional<Double> max = emps.stream() .map(Employee::getSalary) .collect(Collectors.maxBy(Double::compare)); System.out.println(max.get()); //9999.99 Optional<Employee> min = emps.stream() .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(min.get()); //Employee(id=103, name=王五, age=28, salary=3333.33) Double sum = emps.stream() .collect(Collectors.summingDouble(Employee::getSalary)); System.out.println(sum); //48888.840000000004 Double avg = emps.stream() .collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(avg); //6984.120000000001 Long count = emps.stream() .collect(Collectors.counting()); System.out.println(count); //7 DoubleSummaryStatistics dss = emps.stream() .collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getMax()); //9999.99 } 分组&分区 //分组 //按照状态分组 @Test public void testGroup() { Map<Employee.Status, List<Employee>> map = emps.stream() .collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(map); } //分区 //分成 true 和 false 两个区 @Test public void test(){ Map<Boolean, List<Employee>> map = emps.stream() .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000)); System.out.println(map); } //多级分组 @Test public void test6() { Map<Employee.Status, Map<String, List<Employee>>> map = emps.stream() .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> { if (e.getAge() >= 60) { return "老年"; } else if (e.getAge() >= 35) { return "中年"; } else { return "成年"; } }))); System.out.println(map); } 拼接 //连接 @Test public void testJoin(){ String str = emps.stream() .map(Employee::getName) .collect(Collectors.joining("," , "----", "----")); System.out.println(str); } @Test public void test(){ DoubleSummaryStatistics dss = emps.stream() .collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getSum()); System.out.println(dss.getAverage()); System.out.println(dss.getMax()); } -------------------- # 6 基本类型流 vs 对象流 # > **基本类型流(IntStream、LongStream.....),与对象流(Stream)的不同点** > > * IntStream和LongStream有range(start, end)和rangeClosed(start, end)方法,可以生成步长为1的整数范围,前者不包括end,后者包括end > * toArray方法将返回基本类型数组 > * 具有sum、average、max、min方法 > * summaryStatics()方法会产生类型为Int/Long/DoubleSummaryStatistics的对象 > * 可以使用Random类的ints、longs、doubles方法产生随机数构成的流 > * 对象流转换为基本类型流:mapToInt()、mapToLong()、mapToDouble() > * 基本类型流转换为对象流:boxed() -------------------- # 7 并行流 vs 串行流 # > Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作;Stream API可以声明性地通过**parallel()** 与 **sequential()** 在并行流与顺序流之间进行切换; > > **并行流**就是把一个内容(数组或集合)分成多个数据块,并用不同的线程分别处理每个数据块的流;这样一来,你就可以自动把给定操作的工作负荷分配给多核处理器的所有内核,让他们都忙起来;整个过程无需程序员显示实现优化; public static long parallelSum(long n){ return Stream.iterate(1L,i -> i +1) .limit(n) .parallel() .reduce(0L,Long::sum); } ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNzk0OTcz_size_16_color_FFFFFF_t_70][] -------------------- # 8 练习 # > 1. 给定一个数字列表,如何返回一个由每个数的平方构成的列表呢? 给定【1,2,3,4,5】应该返回【1,4,9,16,25】 @Test public void testSquare(){ Integer[] nums = new Integer[]{1,2,3,4,5}; Arrays.stream(nums) .map((x) -> x * x) .forEach(System.out::println); } > 2. 怎样用map和reduce方法数一数流中有多少个Employee呢? @Test public void testCount(){ Optional<Integer> count = emps.stream() .map((e) -> 1) .reduce(Integer::sum); System.out.println(count.get()); } > //交易员类 @Data public class Trader { /**交易员名字*/ private String name; /**交易员城市*/ private String city; public Trader(String name, String city) { this.name = name; this.city = city; } } //交易类 @Data public class Transaction { /**交易员*/ private Trader trader; /**交易年份*/ private int year; /**交易额*/ private int value; public Transaction(Trader trader, int year, int value) { this.trader = trader; this.year = year; this.value = value; } } public class TestTransaction { List<Transaction> transactions; @Before public void before(){ Trader raoul = new Trader("Raoul", "Cambridge"); Trader mario = new Trader("Mario", "Milan"); Trader alan = new Trader("Alan", "Cambridge"); Trader brian = new Trader("Brian", "Cambridge"); 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年发生的所有交易, 并按交易额排序(从低到高) @Test public void test() { transactions.stream() .filter((t) -> t.getYear() == 2011) .sorted((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue())) .forEach(System.out::println); } //2. 交易员都在哪些不同的城市工作过? @Test public void test() { transactions.stream() .map((t) -> t.getTrader().getCity()) .distinct() .forEach(System.out::println); } //3. 查找所有来自剑桥的交易员,并按姓名排序 @Test public void test() { transactions.stream() .filter((t) -> t.getTrader().getCity().equals("Cambridge")) .map(Transaction::getTrader) .sorted((t1, t2) -> t1.getName().compareTo(t2.getName())) .distinct() .forEach(System.out::println); } //4. 返回所有交易员的姓名字符串,按字母顺序排序 @Test public void test() { transactions.stream() .map((t) -> t.getTrader().getName()) .sorted() .forEach(System.out::println); System.out.println("-----------------------------------"); String str = transactions.stream() .map((t) -> t.getTrader().getName()) .sorted() .reduce("", String::concat); System.out.println(str); System.out.println("------------------------------------"); transactions.stream() .map((t) -> t.getTrader().getName()) .flatMap(TestTransaction::filterCharacter) .sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) .forEach(System.out::print); } public static Stream<String> filterCharacter(String str) { List<String> list = new ArrayList<>(); for (Character ch : str.toCharArray()) { list.add(ch.toString()); } return list.stream(); } //5. 有没有交易员是在米兰工作的? @Test public void test() { boolean bl = transactions.stream() .anyMatch((t) -> t.getTrader().getCity().equals("Milan")); System.out.println(bl); } //6. 打印生活在剑桥的交易员的所有交易额 @Test public void test() { Optional<Integer> sum = transactions.stream() .filter((e) -> e.getTrader().getCity().equals("Cambridge")) .map(Transaction::getValue) .reduce(Integer::sum); System.out.println(sum.get()); } //7. 所有交易中,最高的交易额是多少 @Test public void test() { Optional<Integer> max = transactions.stream() .map((t) -> t.getValue()) .max(Integer::compare); System.out.println(max.get()); } //8. 找到交易额最小的交易 @Test public void test() { Optional<Transaction> op = transactions.stream() .min((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue())); System.out.println(op.get()); } // https://www.jb51.net/article/104114.htm // https://zhangzw.com/posts/20191205.html public class ListToMapTest { static List<User> userList = Lists.newArrayList( new User().setId("A").setName("张三"), new User().setId("B").setName("李四"), new User().setId("C").setName("王五"), new User().setId("C").setName("呵呵") ); public static void main(String[] args) { userList.stream().collect(Collectors.toMap( (key) -> { System.out.println(key); return key.getId(); }, (value) -> { System.out.println(value); return value.getName(); }, (v1, v2) -> { System.out.println(">>>>>>>>>>>>(v1, v2)>>>>>>>>>>"); System.out.println(v1); System.out.println(v2); System.out.println(">>>>>>>>>>>>(v1, v2)>>>>>>>>>>"); return v1; } )); System.out.println(userList); } } [https_blog.csdn.net_qq_40794973_article_details_86882454_t32]: https://blog.csdn.net/qq_40794973/article/details/86882454#t32 [https_www.baeldung.com_java-iterable-to-stream]: https://www.baeldung.com/java-iterable-to-stream [https_docs.oracle.com_javase_8_docs_api_java_util_stream_StreamSupport.html]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/StreamSupport.html [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNzk0OTcz_size_16_color_FFFFFF_t_70]: /images/20230528/25adeca7f519403cb7a83d3c37c7564d.png
还没有评论,来说两句吧...