简体   繁体   中英

Why does the Optional ifPresent method give an error when the value is null?

I have a method that returns an Optional value:

ublic Optional<Users> findByUserName(String name) {
        String hqlRequest = "from Users U JOIN FETCH U.roles where U.name =:name";
        Query query = sessionFactory.getCurrentSession().createQuery(hqlRequest).setParameter("name",name);
        return Optional.ofNullable( (Users) query.getResultList().get(0) );
    }

And when in another place I try to print the value

userService.findByUserName("admin2").ifPresent(System.out::println);

If I pass the correct name, then everything works, but why if the name is incorrect (the value is zero), then I get an error:

Caused by: java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0

shouldn't this method skip null values?

The Optional doesn't even get created here. The IndexOutOfBoundsException will be coming from query.getResultList().get(0) - you're trying to get the first element of an empty list, which doesn't exist.

Instead, you could return Optional.empty() if the result list is empty.

To get the desired behavior, ie to get the first element of the result list, or an empty Optional if the result list is empty, change your return statement from

return Optional.ofNullable( (Users) query.getResultList().get(0) );

to

return query.getResultList().stream().map(Users.class::cast).findFirst();

This method returns an instance of this Optional class with the specified value of the specified type.

If the specified value is null, then this method returns an empty instance of the Optional class.

So if the value is null, then it returns Optional.empty as output.

And when you do Optional.ofNullable( (Users) query.getResultList().get(0) ); You get the index out of bounds error.

You will have to first check if the value is not an empty instance of the optional class before you access data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM