Stream流用法示例-创新互联

StreamApi是jdk1.8所提供的新特性,基于lambda表达式,对数据流的一系列操作。数据源可以来自很多地方,可以是数组、集合也可以是文件等等。对于Stream它包含两个操作,中间操作和终止操作,终止操作出现之前是不会进行中间操作的,也就是说想要使用StreamAPI就必须要有一个终止操作,否者代码将不执行。

成都创新互联主要为客户提供服务项目涵盖了网页视觉设计、VI标志设计、营销型网站建设、网站程序开发、HTML5响应式重庆网站建设公司移动网站建设、微商城、网站托管及成都网站维护公司、WEB系统开发、域名注册、国内外服务器租用、视频、平面设计、SEO优化排名。设计、前端、后端三个建站步骤的完善服务体系。一人跟踪测试的建站服务标准。已经为成都阳光房行业客户提供了网站制作服务。
  1. 创建Stream
    1. 通过StreamAPI静态工厂创建
      Streamstream = Stream.of(1,2,3,4,5);
    2. 通过集合Collection默认方法stream()创建
      Listlist = List.of(1,2,3,4,5);
      Streamstream = list.stream();
    3. 通过数组创建
      Integer a[] = new Integer[5];
      Streamstream = Arrays.stream(a);
    4. 通过文件创建文件流
      Streamlines = Files.lines(Paths.get("D://a.txt"));
  2. 使用StreamAPI
    public class StreamApp {
    
        private ListdataList;
    
        @Before
        public void before() {
            dataList = new ArrayList<>(List.of("zhangsan", "lisi", "wangwu", "zhaoliu", "gaoyuanyuan", "xietingfeng", "zhaoliu"));
        }
    
        @Test
        public void testMap() {
            // map操作
            dataList.stream().map(User::new).forEach(System.out::println);
        }
    
        @Test
        public void testFilter() {
            // filter操作
            dataList.stream().filter(name ->name.startsWith("z")).forEach(System.out::println);
        }
    
        @Test
        public void testAllMatch() {
            // allMatch操作
            boolean boo = dataList.stream().allMatch(name ->name.matches("\\D+"));
            System.out.println(boo);
        }
    
        @Test
        public void testAnyMatch() {
            // anyMatch操作
            boolean boo = dataList.stream().anyMatch(name ->name.contains("y"));
            System.out.println(boo);
        }
    
        @Test
        public void testCount() {
            //统计操作
            System.out.println(dataList.stream().count());
        }
    
        @Test
        public void testDistinct() {
            //去重操作
            dataList.stream().distinct().forEach(System.out::println);
        }
    
        @Test
        public void testFindAny() {
            //findAny操作
            System.out.println(dataList.stream().findAny().orElse("liuhf"));
        }
    
        @Test
        public void testFindFirst() {
            // findFirst操作
            System.out.println(dataList.stream().findFirst().orElse("liuhf"));
        }
    
    
        @Test
        public void testFlatMap() {
            // 扁平化
            dataList.stream().flatMap(name->Stream.of(name.split("z"))).forEach(System.out::println);
        }
    
        @Test
        public void testForeach(){
            // 遍历
            dataList.stream().forEach(System.out::println);
        }
    
        @Test
        public void testForeachOrder(){
            dataList.stream().forEachOrdered(System.out::println);
        }
    
        @Test
        public void testLimit(){
            // limit操作
            dataList.stream().limit(2).forEach(System.out::println);
        }
    
        @Test
        public void testMax(){
            // 查大值
            System.out.println(dataList.stream().max(Comparator.comparingInt(n ->n.charAt(0))).orElse("liuhf"));
        }
    
        @Test
        public void testMin(){
            // 查最小值
            System.out.println(dataList.stream().min(Comparator.comparingInt(n ->n.charAt(0))).orElse("liuhf"));
        }
    
        @Test
        public void testNoneMatch(){
            // 查不存在
            System.out.println(dataList.stream().noneMatch(name ->name.startsWith("a")));
        }
    
        @Test
        public void testPeek(){
            // peek 操作
            Listnames = dataList.stream().peek(name ->System.out.println(name.charAt(0))).toList();
        }
    
        @Test
        public void testReduce(){
            // 统计
            int val = Stream.of(1, 2, 3, 4, 5).reduce(Integer::sum).orElse(0);
            System.out.println(val);
            int value = Stream.of(1, 2, 3, 4, 5).reduce(0, Integer::sum);
            System.out.println(value);
            Integer reduce = Stream.of(1, 2, 3, 4, 5).reduce(0, Integer::sum, Integer::sum);
            System.out.println(reduce);
        }
    
        @Test
        public void testSorted(){
            // 排序
            dataList.stream().sorted().forEach(System.out::println);
            System.out.println(">>>>>>>>>>>>>>>>>>>");
            dataList.stream().sorted(Comparator.comparing(x->x.charAt(1))).forEach(System.out::println);
        }
    
        @Test
        public void testToArray(){
            //转换为数组
            Object[] array = dataList.stream().toArray();
            for (Object o : array) {
                System.out.println(o);
            }
            System.out.println(">>>>>>>>>>>>>");
            //可以使用构造引用,为了表诉清楚先这样编写
            for (String s : dataList.stream().toArray(x ->new String[x])) {
                System.out.println(s);
            }
        }
    
    
    
    
        @Test
        public void testSkip(){
            //跳过
            dataList.stream().skip(2).forEach(System.out::println);
        }
    
        static class User {
            String name;
    
            public User(String name) {
                this.name = name;
            }
    
            @Override
            public String toString() {
                return "User{" +
                        "name='" + name + '\'' +
                        '}';
            }
        }
    }

  3. Stream收集器Collector
    public class CollectorApp {
    
        private Listdata;
    
        @Before
        public void before() {
            data = new ArrayList<>(List.of("1", "2", "3", "4", "5"));
        }
    
        @Test
        public void testAveragingInt() {
            //求平均值
            Double collect = data.stream().collect(Collectors.averagingInt(Integer::valueOf));
            System.out.println(collect);
        }
        @Test
        public void testAveragingDouble() {
            //求平均值
            Double collect = data.stream().collect(Collectors.averagingDouble(Double::valueOf));
            System.out.println(collect);
        }
        @Test
        public void testAveragingLong() {
            //求平均值
            Double collect = data.stream().collect(Collectors.averagingLong(Long::valueOf));
            System.out.println(collect);
        }
    
        @Test
        public void testCollectingAndThen(){
            //收集以及做额外的转换
            Setcollect = data.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
        }
    
        @Test
        public void testCounting(){
            Long count = data.stream().collect(Collectors.counting());
            System.out.println(count);
        }
    
        @Test
        public void testGroupingBy(){
            //参数1: 分组函数
            Map>map = data.stream().collect(Collectors.groupingBy(num ->Integer.parseInt(num) % 2 == 0));
            System.out.println(map);
    
            //参数1:分组函数 参数2:收集器类型
            Map>map1 = data.stream().collect(Collectors.groupingBy(num ->Integer.parseInt(num) % 2 == 0, Collectors.toSet()));
            System.out.println(map1);
    
            //参数1:分组函数 参数2:工厂,提供容器类型 参数3:收集器类型
            TreeMap>map2 = data.stream().collect(Collectors.groupingBy(num ->Integer.parseInt(num) % 2 == 0, () ->new TreeMap<>(), Collectors.toSet()));
            System.out.println(map2);
        }
    
        @Test
        public void testJoining(){
            //将元素合并为字符串且无分隔符
            String collect = data.stream().collect(Collectors.joining());
            System.out.println(collect);
    
            String collect1 = data.stream().collect(Collectors.joining(","));
            System.out.println(collect1);
    
            String collect2 = data.stream().collect(Collectors.joining(",", "[", "]"));
            System.out.println(collect2);
        }
    
        @Test
        public void testMapping(){
            // 同stream的map函数,使用频率较少,只在stream的map函数不方便使用是才会选择
            Setcollect = data.stream().collect(Collectors.mapping(Integer::parseInt, Collectors.toSet()));
            System.out.println(collect);
        }
    
        @Test
        public void testMaxBy(){
            // 求大值,同stream的max()
            String max = data.stream().collect(Collectors.maxBy((n1, n2) ->Integer.parseInt(n1) - Integer.parseInt(n2))).orElse("0");
            System.out.println(max);
        }
    
        @Test
        public void testMinBy(){
            // 求最小值,同stream的min()
            String min = data.stream().collect(Collectors.minBy((n1, n2) ->Integer.parseInt(n1) - Integer.parseInt(n2))).orElse("0");
            System.out.println(min);
        }
    
        @Test
        public void testPartitioningBy(){
            //分割,一个特殊分组,只能分出boolean类型的key
            Map>map = data.stream().collect(Collectors.partitioningBy(num ->Integer.parseInt(num) % 2 == 0));
            System.out.println(map);
    
            //提供一个收集器
            Map>map1 = data.stream().collect(Collectors.partitioningBy(num ->Integer.parseInt(num) % 2 == 0,Collectors.toSet()));
            System.out.println(map1);
        }
    
        @Test
        public void testReducing(){
            //同stream函数reduce函数,合并
            String s = data.stream().collect(Collectors.reducing((n1, n2) ->String.valueOf(Integer.parseInt(n1) + Integer.parseInt(n2)))).orElse("0");
            System.out.println(s);
    
            String s1 = data.stream().collect(Collectors.reducing("0",(n1, n2) ->String.valueOf(Integer.parseInt(n1) + Integer.parseInt(n2))));
            System.out.println(s1);
    
            String s2 = data.stream().collect(Collectors.reducing("0",(n)->String.valueOf(Integer.parseInt(n)+1),(n1, n2) ->String.valueOf(Integer.parseInt(n1) + Integer.parseInt(n2))));
            System.out.println(s2);
    
        }
    
        @Test
        public void testSummarizing(){
            //总结
            DoubleSummaryStatistics collect = data.stream().collect(Collectors.summarizingDouble(Double::parseDouble));
            System.out.println(collect);
    
            IntSummaryStatistics collect1 = data.stream().collect(Collectors.summarizingInt(Integer::parseInt));
            System.out.println(collect1);
    
            LongSummaryStatistics collect2 = data.stream().collect(Collectors.summarizingLong(Long::parseLong));
            System.out.println(collect2);
        }
    
        @Test
        public void testSumming(){
    
            //计算总和
            Double aDouble = data.stream().collect(Collectors.summingDouble(Double::parseDouble));
            System.out.println(aDouble);
    
            Integer aInt = data.stream().collect(Collectors.summingInt(Integer::parseInt));
            System.out.println(aInt);
    
            Long aLong = data.stream().collect(Collectors.summingLong(Long::parseLong));
            System.out.println(aLong);
        }
    
        @Test
        public  void testToList(){
            Listcollect = data.stream().collect(Collectors.toList());
        }
    
        @Test
        public void testToSet(){
            Setcollect = data.stream().collect(Collectors.toSet());
        }
    
        @Test
        public void testCollection(){
            LinkedListcollect = data.stream().collect(Collectors.toCollection(LinkedList::new));
        }
    
        @Test
        public void testToMap(){
            Mapcollect1 = data.stream().collect(Collectors.toMap(k ->Integer.parseInt(k) + 1, v ->v));
            Mapcollect2 = data.stream().collect(Collectors.toMap(k ->Integer.parseInt(k) + 1, v ->v,(n1,n2)->String.valueOf(Integer.parseInt(n1)+Integer.parseInt(n2))));
            Mapcollect3 = data.stream().collect(Collectors.toMap(k ->Integer.parseInt(k) + 1, v ->v,(n1,n2)->String.valueOf(Integer.parseInt(n1)+Integer.parseInt(n2)),TreeMap::new));
            System.out.println(collect1);
            System.out.println(collect2);
            System.out.println(collect3);
    
            //toConcurrentMap同toMap一样,只是Map为线程安全的ConcurrentMap
        }
    }

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网页标题:Stream流用法示例-创新互联
网址分享:http://myzitong.com/article/dgedgc.html