Lambda与Stream流

114 阅读2分钟

Lambda和Stream流

1. 创建流

1.1 集合创建

list.stream();
set.stream();
map.entrySet().stream();

1.2 数组创建

Arrays.stream(arr);

2. 使用流

map

流类型转换,可以使用匿名内部类或者Lamdba以及方法引用

public void test() {
    Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    Arrays.stream(arr)
        .map(a -> String.valueOf(a))
        .forEach(System.out::println);
    Arrays.stream(arr)
        .map(String::valueOf)
        .forEach(System.out::println);
}
output : 1, 2, 3, 4, 5, 6, 7, 8, 9 but type is String

distinct

去重

public void test() {
    Integer[] arr = {1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9};
    Arrays.stream(arr)
        .distinct()
        .map(a -> String.valueOf(a))
        .forEach(System.out::println);
    Arrays.stream(arr)
        .distinct()
        .map(String::valueOf)
        .forEach(System.out::println);
}
output : 1, 2, 3, 4, 5, 6, 7, 8, 9 but type is String

filter

过滤流,接口内的方法返回boolean,true时保留,false时过滤

public void test() {
    Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    Arrays.stream(arr)
        .filter(a -> a > 4)
        .map(a -> String.valueOf(a))
        .forEach(System.out::println);
    Arrays.stream(arr)
        .filter(a - a > 4)
        .map(String::valueOf)
        .forEach(System.out::println);
}
output : 5, 6, 7, 8, 9 but type is String

flatMap

map只能处理一个流对象,flatMap可以处理多个

 public static void test() {
     List<Integer[]> list = new ArrayList<>();
     Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
     list.add(arr)
        list.stream()
                .flatMap(Arrays::stream)
                .forEach(System.out::println);
    }
output : 1, 2, 3, 4, 5, 6, 7, 8, 9

3. 关闭流

collect

使用Collectors,可以转换为多种类型

public static void test6() {
    Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        Arrays.stream(arr)
                .map(String::valueOf)
                .collect(Collectors.toSet());
    }

forEach

遍历流

reduce

将流计算为一个结果

public void test() {
    Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    Optional<Integer> reduce = Arrays.stream(arr)
        .reduce(Integer::sum);
    reduce.ifPresent(System.out::println);
}
output : 45

3.Optional

避免空指针异常

1. 创建Optional

Optional.ofNullable(obj);
//如果确定objbu为null可以使用
Optional.of(obj);
//如果obj=null,则出现空指针异常
//null的OPtional时empty
Optional.empty();
Author author = null;
        Optional<Author> author1 = Optional.ofNullable(author);
        author1.ifPresent(a -> System.out.println(a.getAge()));

2. 消费

ifPersent()

3.获取

get() 不推荐 ,没有值时报错

orElseGet(),没有值时,有default

orElseThrow,没有值时,报异常

4.过滤

filter()

5. 判断

isPresent()

6.数据转换

Stream一样,map()flatMap( )

喜欢的句子

宿舍里有一股味,找了好久没有找到,原来是枕头里藏着发了霉的梦,和我腐烂的梦想,谁没奢求过一场骗自己的幻想,这被世人称作梦。

反正公众号也没有人关注,我可以大胆的说出我的梦想:

我想当一个非常厉害的程序员,在大厂工作,认识一些厉害的人。等明年找到工作了,我要说一说我这几年是怎么过来的,真的是独行。 pCsgLHx.jpg

本文由mdnice多平台发布