JDK1.8新特性之steam流,常规用法

一、集合合并

public class test{
    /**
     * 把小王合道
     * list中
     * */
    public static void main(String [] args) throws Exception {
        final ArrayList<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        final ArrayList<String> strings = new ArrayList<>();
        strings.add("小王");
        //合并集合concat
        //list.stream()获取流对象
        Stream.concat(list.stream(),strings.stream()).forEach(System.out::println);
    }
}

二、字段过滤

public class test{
    /**
     * 把小王合道
     * list中
     * */
    public static void main(String [] args) throws Exception {
        final ArrayList<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        filter 过滤 已前缀过滤 s.length他的长度为3的
 list.stream().filter(s -> s.startsWith("张")).filter(s -> s.length()==3).forEach(System.out::println);
    }
}

三、集合去重

public class test{
    public static void main(String[] args) {
        //去重,加强效能
 data = data.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OperationDTO::getId))), ArrayList::new));
    }
}

四、集合排序

public class test{
    /**
     * list中
     * */
    public static void main(String [] args) throws Exception {
        final ArrayList<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(8);
        list.add(1);
     //原始排序(默认是顺序) 也可以使用冒泡排序 或者快速排序 这个是调用java中的工具类实现的排序
        /*    Collections.sort(list);*/
        //倒叙排列
        /*   Collections.reverse(list);*/
        //从大到小排列
        //Collections.sort(list,Collections.reverseOrder());
        list.stream().sorted().forEach(System.out::println);
        //System.out.println(list);
    }
}

五、数组转集合

  public static void main(String [] args) throws Exception {
        int[] a = {1, 2, 3, 4, 5};
        final List<Integer> collect = Arrays.stream(a).boxed().collect(Collectors.toList());
        System.out.println(collect);
    }}

六、通过流找到数组中最大值

public class test{
    /**
     * list中
     * */
    public static void main(String [] args) throws Exception {
        int[] a = {1, 2, 3, 4, 5};
        final OptionalInt max = Arrays.stream(a).max();
        System.out.println(max);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值