Java8 新特性 Steam() 中间有状态操作

中间有状态操作

Java8 新特性 Stream 练习实例

  中间操作,就是把数据处理成自己想要的类型,并且有状态操作,是在所有的数据基础上进行操作的。比如dictinct(去重),sorted(排序)....

所有的有状态操作:

去重 distinct
跳过 skip
截断 limit
排序 sorted

去重 distinct

//找出所有的对象的类型
@Test
public void test1() {
    list.stream()
        //找出所有的对象的类型
        .map(Sku::getSkuCategory)
        //然后去重
        .distinct()
        .forEach(System.out::println);
}
/*
ELECTRONICS
CLOTHING
SPORTS
BOOKS
*/

跳过 skip

/**
 * 跳过 skip
 */
@Test
public void test2() {
    //没有过滤
    list.stream()
            .forEach(item -> System.out.println(
                    JSON.toJSONString(
                            item.getSkuId(), true)));

    long count = list.stream().count();
    System.out.println("总共有" + count + "个对象");

    //跳过 skip
    list.stream()
            //跳过前7个
            .skip(7)
            .forEach(item -> System.out.println(
                    JSON.toJSONString(
                            item.getSkuId(), true)));
    /**
     * 输出的结果:
     * 100001
     * 100002
     * 100003
     * 100004
     * 100005
     * 100006
     * 100007
     * 100008
     * 100009
     * 总共有9个对象
     * 100007
     * 100008
     * 从1开始,到第7个开始获取
     */
    }

截断 limit

/**
 * 截断 limit
 */
@Test
public void limitTest() {
    list.stream()
            //截断
            .limit(1)
            //输出
            .forEach(item ->
                    System.out.println(
                        JSON.toJSONString(item,true)));

    /**
     * 只截断了第一个
     * 剩下来的全部都丢弃
     *  "skuCategory":"ELECTRONICS",
     *  "skuId":100001,
     *  "skuName":"无人机",
     *  "skuPrice":4999.0,
     *  "totalNum":1,
     *  "totalPrice":4999.0
     * 
     */
}

排序 sorted

/**
     * sorted 排序
     */
    @Test
    public void sortedTest() {
        List<Double> collect = list.stream()
                //排序
                .sorted(Comparator.comparing(Sku::getSkuPrice))
                //映射成只有价格
                .map(Sku::getSkuPrice)
                //把经果收集成价格列表
                .collect(Collectors.toList());
        //循环输出出来
        collect.forEach(System.out::println);
        /**
         * //价格升序排列,倒序排列:reversed 在 comparing 加上去
         * 78.2
         * 79.8
         * 85.5
         * 149.0
         * 409.0
         * 528.0
         * 2299.0
         * 2699.0
         * 4999.0
         */



细节决定成败!

个人愚见,如有不对,恳请扶正!

猜你喜欢

转载自www.cnblogs.com/xdtg/p/12000528.html