<span>Java8 stream流 基本用例、用法</span>

1. 处理 List <string> 三种方式对比 </string>

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;
    }
}

全部评论

相关推荐

头像
10-13 18:10
已编辑
东南大学 C++
。收拾收拾心情下一家吧————————————————10.12更新上面不知道怎么的,每次在手机上编辑都会只有最后一行才会显示。原本不想写凉经的,太伤感情了,但过了一天想了想,凉经的拿起来好好整理,就像象棋一样,你进步最快的时候不是你赢棋的时候,而是在输棋的时候。那废话不多说,就做个复盘吧。一面:1,经典自我介绍2,项目盘问,没啥好说的,感觉问的不是很多3,八股问的比较奇怪,他会深挖性地问一些,比如,我知道MMU,那你知不知道QMMU(记得是这个,总之就是MMU前面加一个字母)4,知不知道slab内存分配器-&gt;这个我清楚5,知不知道排序算法,排序算法一般怎么用6,写一道力扣的,最长回文子串反问:1,工作内容2,工作强度3,关于友商的问题-&gt;后面这个问题问HR去了,和中兴有关,数通这个行业和友商相关的不要提,这个行业和别的行业不同,别的行业干同一行的都是竞争关系,数通这个行业的不同企业的关系比较微妙。特别细节的问题我确实不知道,但一面没挂我。接下来是我被挂的二面,先说说我挂在哪里,技术性问题我应该没啥问题,主要是一些解决问题思路上的回答,一方面是这方面我准备的不多,另一方面是这个面试写的是“专业面试二面”,但是感觉问的问题都是一些主管面/综合面才会问的问题,就是不问技术问方法论。我以前形成的思维定式就是专业面会就是会,不会就直说不会,但事实上如果问到方法论性质的问题的话得扯一下皮,不能按照上面这个模式。刚到位置上就看到面试官叹了一口气,有一些不详的预感。我是下午1点45左右面的。1,经典自我介绍2,你是怎么完成这个项目的,分成几个步骤。我大致说了一下。你有没有觉得你的步骤里面缺了一些什么,(这里已经在引导我往他想的那个方向走了),比如你一个人的能力永远是不够的,,,我们平时会有一些组内的会议来沟通我们的所思所想。。。。3,你在项目中遇到的最困难的地方在什么方面4,说一下你知道的TCP/IP协议网络模型中的网络层有关的协议......5,接着4问,你觉得现在的socket有什么样的缺点,有什么样的优化方向?6,中间手撕了一道很简单的快慢指针的问题。大概是在链表的倒数第N个位置插入一个节点。————————————————————————————————————10.13晚更新补充一下一面说的一些奇怪的概念:1,提到了RPC2,提到了fu(第四声)拷贝,我当时说我只知道零拷贝,知道mmap,然后他说mmap是其中的一种方式,然后他问我知不知道DPDK,我说不知道,他说这个是一个高性能的拷贝方式3,MMU这个前面加了一个什么字母我这里没记,别问我了4,后面还提到了LTU,VFIO,孩子真的不会。
走呀走:华子二面可能会有场景题的,是有些开放性的问题了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务