How to best create a Java 8 stream from a nullable object?

后端 未结 6 1676
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 02:01

What is the best/idiomatic way of doing a null check before getting a stream?

I have method that is receiving a List that might be null. So I can\'t jus

6条回答
  •  独厮守ぢ
    2020-12-09 02:23

    The best thing I can think of would be to use an Optional with the orElseGet method.

    return Optional.ofNullable(userList)
                    .orElseGet(Collections::emptyList)
                    .stream()
                    .map(user -> user.getName())
                    .collect(toList());
    

    Updated with @Misha's suggest to use Collections::emptyList over ArrayList::new

提交回复
热议问题