Stream 示例

建立一個無限大小的Stream

Stream s = Stream.generate(()->1);
//測試循環10次
 s.peek(System.out::println).limit(10).collect(Collectors.toList());

建立一個1到100的數字,而後求和

IntStream s = IntStream.iterate(1,t->t+1).limit(100);
        //s = IntStream.range(1,100)
        System.out.println(s.sum());

分組

類以下:java

static class Stu {

        public static Stu get(String name, String sex, String clas) {
            Stu s = new Stu();
            s.name = name;
            s.sex = sex;
            s.clas = clas;
            return s;
        }

        public String name;

        public String sex;

        public String clas;

        public String getName() {
            return name;
        }

        public String getClas() {
            return clas;

        }

        public String getSex() {
            return sex;

        }
    }

測試類 按clas分組spring

Stu s1 = Stu.get("a1","F","A");
        Stu s2 = Stu.get("a2","M","A");
        Stu s3 = Stu.get("a3","F","B");
        Stu s4 = Stu.get("a4","M","B");

        System.out.println(Stream.of(s1,s2,s3,s4).collect(Collectors.groupingBy(Stu::getClas)));

按clas,sex分組測試

Stream.of(s1,s2,s3,s4).collect(Collectors.groupingBy(Stu::getClas,Collectors.groupingBy(Stu::getSex)))

分區

按是與否分2個區,3d

Stream.of(s1,s2,s3,s4).collect(Collectors.partitioningBy(t->StringUtils.equals(t.sex,"F")))

運行後結果:code

{false=[spring.B$Stu@246b179d, spring.B$Stu@7a07c5b4], true=[spring.B$Stu@26a1ab54, spring.B$Stu@3d646c37]}

將Stu對象的name組成一個字符串,用:分隔

Stream.of(s1,s2,s3,s4).map(Stu::getName).collect(Collectors.joining(":"))
相關文章
相關標籤/搜索