java1.8 新特性(关于 match,find reduce )操作

原文:https://www.cnblogs.com/920913cheng/p/10240219.html

     1. match处理Integer集合

package lambda.stream;
/**    
* @author 作者:cb   
* @version 创建时间:2019年1月4日 下午2:35:05 
         
*/

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo {
    public static void main(String[] args) {
        testMatch();
    }

    public static void testMatch() {
        List<Integer> asList = Arrays.asList(1, 2, 3);
        // 必须满足任何一个元素 都 小于5 才返回true 有一个元素大于5 都会返回false
        boolean allMatch = asList.stream().allMatch(i -> i < 5);
        System.out.println(allMatch);
        List<Integer> asList1 = Arrays.asList(8, 9, 10);
        // 必须满足任何一个元素 都不能 小于5 才返回true 有一个元素小于5 都会返回false
        boolean noneMatch = asList1.stream().noneMatch(i -> i < 5);
        System.out.println(noneMatch);
        List<Integer> asList2 = Arrays.asList(8, 9, 3);
        // 只要有任何一个元素 小于 5 都返回true
        boolean anyMatch = asList2.stream().anyMatch(i -> i < 5);
        System.out.println(anyMatch);

    }

结果:

true
true
true
  1. find 
    复制代码
    package lambda.stream;
    /**    
    * @author 作者:cb   
    * @version 创建时间:2019年1月4日 下午2:35:05 
             
    */
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class StreamDemo {
        public static void main(String[] args) {
            testFind();
        }
    
        public static void testFind() {
            List<Integer> asList = Arrays.asList(5, 2, 3);
            // 从该list中获取第一个元素
            Integer num = asList.stream().findFirst().get();
            System.out.println(num);
            Integer anyNum = asList.stream().findAny().get();
            System.out.println(anyNum);
        }
    复制代码

    结果:

    5
    5
  2. reduce 实现一个集合的累加

    复制代码
    package lambda.stream;
    /**    
    * @author 作者:cb   
    * @version 创建时间:2019年1月4日 下午2:35:05 
             
    */
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class StreamDemo {
        public static void main(String[] args) {
            testReduce();
        }
    
        public static void testReduce() {
            List<Integer> asList = Arrays.asList(5, 2, 3);
            // 实现该集合的累加
            Integer reduce = asList.stream().reduce(0, (i, j) -> i + j);
            System.out.println(reduce);
            // 实现该集合的乘积
            Integer reduce1 = asList.stream().reduce(1, (i, j) -> i * j);
            System.out.println(reduce1);
    
        }
    复制代码

    结果:

    10
    30
原文地址:https://www.cnblogs.com/lshan/p/12837627.html