Java8 stream流 基本用例、用法

1. 处理 List 三种方式对比

public static void main(String[] args) {
        // 1. 添加测试数据:存储多个账号的列表
        List<String> accounts = new ArrayList<String>();
        accounts.add("tom");
        accounts.add("jerry");
        accounts.add("beita");
        accounts.add("shuke");
        accounts.add("damu");

        // 1.1. 业务要求:长度大于等于5的有效账号
        for (String account : accounts) {
            if (account.length() >= 5) {
                System.out.println("有效账号:"  + account);
            }
        }

        // 1.2. 迭代方式进行操作
        Iterator<String> it = accounts.iterator();
        while(it.hasNext()) {
            String account = it.next();
            if (account.length() >= 5) {
                System.out.println("it有效账号:" + account);
            }
        }

        // 1.3. Stream结合lambda表达式,完成业务处理
        List validAccounts = accounts.stream().filter(s->s.length()>=5).collect(Collectors.toList());
        System.out.println(validAccounts);

    }

2.Stream流 的各种接口使用用例

public static void main(String[] args) {
        // list -> stream
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
        System.out.println(list);

        // map(Function(T, R)-> R) 接受一个参数,通过运算得到转换后的数据
        // collect()
        List<Double> list2 = list.stream().map(x->Math.pow(x, 2)).collect(Collectors.toList());
        System.out.println(list2);

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");

        // arrays -> stream
        Integer [] nums = new Integer[]{1,2,3,4,5,6,7,8,9,10};
        System.out.println(Arrays.asList(nums));

        // filter(Predicate(T t)->Boolean) 接受一个参数,验证参数是否符合设置的条件
        // toArray() 从Stream类型抽取数据转换成数组
        Integer [] nums2 = Stream.of(nums).filter(x -> x % 2 == 0).toArray(Integer[]::new);
        System.out.println(Arrays.asList(nums2));

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");
        // forEach: 接受一个lambda表达式,在Stream每个元素上执行指定的操作
        list.stream().filter(n->n%2==0).forEach(System.out::println);

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");

        List<Integer> numList = new ArrayList<>();
        numList.add(1);
        numList.add(3);
        numList.add(2);
        numList.add(5);
        numList.add(4);
        numList.add(6);

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");
        // reduce
        Optional<Integer> sum = numList.stream().reduce((x, y) -> x + y);
        System.out.println(sum.get());

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");
        // limit
        List limitNum = numList.stream().limit(2).collect(Collectors.toList());
        System.out.println(limitNum);

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");
        // skip
        List limitNum2 = numList.stream().skip(2).collect(Collectors.toList());
        System.out.println(limitNum2);

        System.out.println("~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~");
        // sorted().一般在skip/limit或者filter之后进行
        List sortedNum = numList.stream().skip(2).limit(5).sorted().collect(Collectors.toList());
        System.out.println(sortedNum);

        // min/max/distinct
        Integer minNum = numList.stream().min((o1, o2)->{return o1-o2;}).get();
        System.out.println(minNum);
        Integer maxNum = numList.stream().max((o1, o2)->o1-o2).get();
        System.out.println(maxNum);
    }

3.效率对比

public class Test {

    public static void main(String[] args) {

        Random random = new Random();
        // 1. 基本数据类型:整数
//        List<Integer> integerList = new ArrayList<Integer>();
//
//        for(int i = 0; i < 1000000; i++) {
//            integerList.add(random.nextInt(Integer.MAX_VALUE));
//        }
//
//        // 1) stream
//        testStream(integerList);
//        // 2) parallelStream
//        testParallelStream(integerList);
//        // 3) 普通for
//        testForloop(integerList);
//        // 4) 增强型for
//        testStrongForloop(integerList);
//        // 5) 迭代器
//        testIterator(integerList);

        // 2. 复杂数据类型:对象
        List<Product> productList = new ArrayList<>();
        for(int i = 0; i < 1000000; i++) {
            productList.add(new Product("pro" + i, i, random.nextInt(Integer.MAX_VALUE)));
        }

        // 调用执行
        testProductStream(productList);
        testProductParallelStream(productList);
        testProductForloop(productList);
        testProductStrongForloop(productList);
        testProductIterator(productList);

    }

    public static void testStream(List<Integer> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max(Integer::compare);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testStream:" + (end - start) + "ms");
    }

    public static void testParallelStream(List<Integer> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.parallelStream().max(Integer::compare);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testParallelStream:" + (end - start) + "ms");
    }

    public static void testForloop(List<Integer> list) {
        long start = System.currentTimeMillis();

        int max = Integer.MIN_VALUE;
        for(int i = 0; i < list.size(); i++) {
            int current = list.get(i);
            if (current > max) {
                max = current;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testForloop:" + (end - start) + "ms");
    }

    public static void testStrongForloop(List<Integer> list) {
        long start = System.currentTimeMillis();

        int max = Integer.MIN_VALUE;
        for (Integer integer : list) {
            if(integer > max) {
                max = integer;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testStrongForloop:" + (end - start) + "ms");
    }

    public static void testIterator(List<Integer> list) {
        long start = System.currentTimeMillis();

        Iterator<Integer> it = list.iterator();
        int max = it.next();

        while(it.hasNext()) {
            int current = it.next();
            if(current > max) {
                max = current;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testIterator:" + (end - start) + "ms");
    }


    public static void testProductStream(List<Product> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testProductStream:" + (end - start) + "ms");
    }

    public static void testProductParallelStream(List<Product> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testProductParallelStream:" + (end - start) + "ms");
    }

    public static void testProductForloop(List<Product> list) {
        long start = System.currentTimeMillis();

        Product maxHot = list.get(0);
        for(int i = 0; i < list.size(); i++) {
            Product current = list.get(i);
            if (current.hot > maxHot.hot) {
                maxHot = current;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductForloop:" + (end - start) + "ms");
    }

    public static void testProductStrongForloop(List<Product> list) {
        long start = System.currentTimeMillis();

        Product maxHot = list.get(0);
        for (Product product : list) {
            if(product.hot > maxHot.hot) {
                maxHot = product;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductStrongForloop:" + (end - start) + "ms");
    }

    public static void testProductIterator(List<Product> list) {
        long start = System.currentTimeMillis();

        Iterator<Product> it = list.iterator();
        Product maxHot = it.next();

        while(it.hasNext()) {
            Product current = it.next();
            if (current.hot > maxHot.hot) {
                maxHot = current;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductIterator:" + (end - start) + "ms");
    }

}

class Product {
    String name;    // 名称
    Integer stock;  // 库存
    Integer hot;    // 热度

    public Product(String name, Integer stock, Integer hot) {
        this.name = name;
        this.stock = stock;
        this.hot = hot;
    }
}

posted @ 2021-06-03 14:37  _lemonV  阅读(144)  评论(0编辑  收藏  举报