目录
  • 一、stream的使用
    • 二、stream的特性
      • 4.1 allmatch
      • 4.2anymatch
      • 4.3nonematch
      • 4.4 findfirst()
      • 4.5 findany()
      • 4.9 foreach

一、stream的使用

1.1 创建

  • 通过collection接口的实现类提供的 stream()方法,或
  • 通过arrays中的静态方法 stream()获取
  • 通过stream类中的静态方法 of()
  • 无限流(迭代/生成)
/**
 * @author: 郜宇博
 * @date: 2021/9/1 23:28
 * 流操作
 */
public class streamtests {
    @test
    public void test(){
        //1.通过collection接口的实现类提供的 stream()方法,或
        collection<string> list = new arraylist<>();
        list.stream();
        list.parallelstream();
        //2.通过arrays中的静态方法 stream()获取
        integer[] integers = new integer[10];
        arrays.stream(integers);
        //3.通过stream类中的静态方法 of()
        stream<string> stream = stream.of("1","2");
        //4.无限流
        //迭代
        stream<integer> iterate = stream.iterate(0, (x) -> x + 2);
        //生成
        stream<double> generate = stream.generate(() -> math.random());
    }
}

1.1.1并行流parallelstream

parallelstream提供了流的并行处理,它是stream的另一重要特性,其底层使用fork/join框架实现。简单理解就是多线程异步任务的一种实现。

1.2 步骤

  • 创建stream;
  • 转换stream,每次转换原有stream对象不改变,返回一个新的stream对象(可以有多次转换);
  • 对stream进行聚合(reduce)操作,获取想要的结果;

二、stream的特性

惰性求值:

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何处理!而是在终止操作时一次性全部处理,这种情况称为“惰性求值”。

三、中间操作

筛选与切片

3.1 filter()

接受lambda表达式,从流中排除某些元素

@test
public void test2(){
    //获取一个数组
    arraylist<integer> arraylist = new arraylist<>();
    for (int i = 0; i <10; i++) {
        arraylist.add(i);
    }
    //流操作:获取大于5的
    arraylist.stream().filter((num)->num>5).foreach(system.out::println);
}
//结果:  6 7 8 9


3.2 limit()

截断流,使其元素个数不超过一定数量

满足limit的数量后,就短路,不在执行后续操作

@test
public void test2(){
    //获取一个数组
    arraylist<integer> arraylist = new arraylist<>();
    for (int i = 0; i <10; i++) {
        arraylist.add(i);
    }
    //流操作:获取大于5的
    arraylist.stream().filter((num)->num>5)
                    .limit(2)
                    .foreach(system.out::println);
}
//结果: 6 7


3.3 skip()

跳过元素,跳过前n个元素,执行后面的元素,如果不足n个则返回空流

@test
public void test2(){
    //获取一个数组
    arraylist<integer> arraylist = new arraylist<>();
    for (int i = 0; i <10; i++) {
        arraylist.add(i);
    }
    //流操作:获取大于5的
    arraylist.stream().filter((num)->num>5)
                    .skip(2)
                    .foreach(system.out::println);
}
//结果: 8 9
3.3 map()
映射,在方法中使用方法function< t> 函数型接口 -----> r apply(t t);

@test
public void  test4(){
    //获取一个list
    list<string> list = arrays.aslist("aaa","bbb","ccc");
    //使用流操作 转化大写
    list.stream().map((str)->str.touppercase())
            .foreach(system.out::println);
}
/*结果:aaa
  bbb
        ccc*/
@test
public void test3(){
    //获取一个list
    list<string> list = arrays.aslist("aaa","bbb","ccc");
    //流操作: 将list中的元素取出
    //第一步使用map取出流,流里存放的还是流
    //因此需要二次foreach
    stream<stream<character>> chs = list.stream().map(streamtests::getupper);
            chs.foreach((stream)->{
                stream.foreach(system.out::print);
            });
}
//将str返回为流对象
public static stream<character> getupper(string str){
    list<character> list = new arraylist<>();
    for (character character: str.tochararray()){
        list.add(character);
    }
    return list.stream();
}
//结果:aaabbbccc

3.4 map()

映射,在方法中使用方法function< t> 函数型接口 —–> r apply(t t);

@test
public void  test4(){
    //获取一个list
    list<string> list = arrays.aslist("aaa","bbb","ccc");
    //使用流操作 转化大写
    list.stream().map((str)->str.touppercase())
            .foreach(system.out::println);
}
/*结果:aaa
  bbb
        ccc*/


@test
public void test3(){
    //获取一个list
    list<string> list = arrays.aslist("aaa","bbb","ccc");
    //流操作: 将list中的元素取出
    //第一步使用map取出流,流里存放的还是流
    //因此需要二次foreach
    stream<stream<character>> chs = list.stream().map(streamtests::getupper);
            chs.foreach((stream)->{
                stream.foreach(system.out::print);
            });
}
//将str返回为流对象
public static stream<character> getupper(string str){
    list<character> list = new arraylist<>();
    for (character character: str.tochararray()){
        list.add(character);
    }
    return list.stream();
}
//结果:aaabbbccc

3.3.1 flatmap

相当于集合方法的 addall

即:将流中的流内元素取出,放入一个流中,而不是流内套流

@test
public void test3(){
    //获取一个list
    list<string> list = arrays.aslist("aaa","bbb","ccc");
    //流操作: 将list中的元素取出
    //第一步使用map取出流,流里存放的还是流
    //因此需要二次foreach
    stream<stream<character>> chs = list.stream().map(streamtests::getupper);
            chs.foreach((stream)-> stream.foreach(system.out::print));

    system.out.println("\n=====");
    //方法二:
    //使用flatmap
    list.stream().flatmap(streamtests::getupper).foreach(system.out::print);
}


3.5 sorted

@test
public void test5(){
    list<string> list = arrays.aslist("aaa", "ccc", "bbbb", "eeeee");
    //自然排序
    list.stream()
            .sorted()
            .foreach(system.out::println);
    system.out.println("=============");
    //定制排序
    list.stream()
            .sorted((x,y)->{
                //如果长度一样,则按照字典排序
                if (x.length() == y.length()){
                    return x.compareto(y);
                }
                //如果长度不一样则按照长度的降序排序
                else {
                    return y.length() - x.length();
                }
            })
            .foreach(system.out::println);

}
/*结果:
aaa
bbbb
ccc
eeeee
=============
eeeee
bbbb
aaa
ccc
*/

四、终止操作

查找与匹配

4.1 allmatch

predicate<? super t> predicate
/**
 * @author: 郜宇博
 * @date: 2021/9/3 14:00
 * 终止操作
 */
public class finaloperation {
    static arraylist<student> list;
    /**
     * allmath 检查是否全部元素符合
     */
    @beforeeach
    public void before(){
        //准备集合
        student student1 = new student(10,"张三", student.status.sad);
        student student2 = new student(20,"李四", student.status.happy);
        student student3 = new student(30,"王五", student.status.free);
        student student4 = new student(18,"田七", student.status.free);
        student student5 = new student(140,"赵六", student.status.tired);
        list = new arraylist<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
    }
}
class student{
    private int age;
    private string name;
    private status status;

    public int getage() {
        return age;
    }

    public string getname() {
        return name;
    }

    public status getstatus() {
        return status;
    }

    /**
     * 枚举状态
     */
    public enum status{
        free,tired,happy,sad;
    }

    public student(int age, string name, status status) {
        this.age = age;
        this.name = name;
        this.status = status;
    }
}
/**
     * 是否全部年龄都大于20
     */
    @test
    public void test1(){
        boolean b = list.stream().allmatch((s) -> s.getage() > 20);
        system.out.println(b);
    }
//结果: false

4.2anymatch

predicate<? super t> predicate
/**
 * 是否存在年龄大于20的
 */
@test
public void test2(){
    boolean b = list.stream().anymatch((s) -> s.getage() > 20);
    system.out.println(b);
}
//结果:true

4.3nonematch

predicate<? super t> predicate
/**
 * 是否没有满足年龄大于20的
 *
 */
@test
public void test3(){
    boolean b = list.stream().nonematch((s) -> s.getage() > 20);
    system.out.println(b);
}
//结果:false

4.4 findfirst()

返回第一元素,但结果可能为null, 因此使用optional<t> 来接收,如果为null则可以替换。

/**
 * 返回第一元素
 */
@test
public void test4(){
    optional<student> first = list.stream()
            .filter((e) -> e.getstatus().equals(student.status.free))
            .findfirst();
    system.out.println(first);
}
//结果:optional[student{age=30, name='王五', status=free}]

4.5 findany()

返回任意一个

/**
 * 返回任意一个
 *
 */
@test
public void test5(){
    optional<student> b = list.parallelstream()
            .filter((student -> student.getage()<30))
            .findany();
     system.out.println(b.get());
}
//结果: 任意一个年龄小于30的学生

4.6 count

/**
 * 获取数量count
 */
@test
public void test6(){
    long count = list.stream().count();
    system.out.println(count);
}
//结果 : 5

4.7 max

/**
     * 获得最大值
     */
    @test
    public void test7(){
        optional<integer> max = list.stream()
                .map(x->x.getage())
                .max(integer::compare);
        system.out.println(max.get());

    }
//结果: 140

4.8 min

/**
 * 获得最小值
 */
@test
public void test7(){
    optional<integer> max = list.stream()
            .map(x->x.getage())
            .min(integer::compare);
    system.out.println(max.get());
}

4.9 foreach

@test
public void test2(){
    //获取一个数组
    arraylist<integer> arraylist = new arraylist<>();
    for (int i = 0; i <10; i++) {
        arraylist.add(i);
    }
    //流操作:获取大于5的
    arraylist.stream().filter((num)->num>5)
                    .limit(2)
                    .foreach(system.out::println);
}
//结果: 6 7

4.10 reduce

/**
     * 归纳
     */
    @test
    public void test8(){
        integer reduce = list.stream()
                .map(student::getage)
                .reduce(0, (x, y) -> x + y);
        system.out.println(reduce);
        //方法二:
        //此方法有可能为null,因此封装为optional对象
        optional<integer> reduce1 = list.stream()
                .map(student::getage)
                .reduce(integer::sum);
        system.out.println(reduce1.get());
    }

4.11 collect

可以收集为集合类,

可以在收集后进行分组、多级分组、分片

/**
 * 收集
 */
@test
public void test9(){
    list<student> collect = list.stream().collect(collectors.tolist());
    collect.foreach(system.out::println);
    //方式二:
    hashset<student> collect1 = list.stream().collect(collectors.tocollection(hashset::new));
    collect.foreach(system.out::println);
}
/*
结果:student{age=10, name='张三', status=sad}
student{age=20, name='李四', status=happy}
student{age=30, name='王五', status=free}
student{age=18, name='田七', status=free}
student{age=140, name='赵六', status=tired}
*/
/**
 * 使用收集可以计算最大值、最小值、平均值、等
 * 也可以进行分组
 */
@test
public void test10(){
    map<student.status, list<student>> collect = list.stream().collect(collectors.groupingby((x) -> x.getstatus()));
    system.out.println(collect.size());
    system.out.println(collect);
}

到此这篇关于java8 stream学习的文章就介绍到这了,更多相关java8 stream内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!