Is there better alternative to making an optional set of elements from iterable in java? I'm feeling uneasy with this service method that I wrote:

    @Override
    public Optional&lt;Set&lt;TenantDTO&gt;&gt; getAllTenantsOfUsers(Set&lt;Long&gt; usersIds) {

        return Optional.ofNullable(usersIds)
                .map((ids) -&gt; tenantRepository.findAll(QTenant.tenant.users.any().id.in(usersIds)))
                .map((it) -&gt; StreamSupport.stream(it.spliterator(), false))
                .map((strm) -&gt; strm.map((tenant) -&gt; tenantMapper.toDto(tenant)).collect(Collectors.toSet()));

    }



My tenantRepository.findAll returns an iterable of Tenant entity

Is this the better approach to get all performance, with good code?
Both optional collection and a collection of optionals are anti-patterns. There is no scenario where returning Optional&lt;Set&lt;X&gt;&gt; or Set&lt;Optional&lt;X&gt;&gt; is preferable to returning a Set&lt;X&gt; that can be empty.

As @AJNeufeld mentions, a guard condition is a good way to start. In your case. If incoming usersIds are null then return an empty set.

public Set&lt;TenantDTO&gt; getAllTenantsOfUsers(Set&lt;Long&gt; usersIds) {
    if (usersIds == null) {
        return Collections.emptySet();
    }
    // ...
}


Its really confusing when you mix Optional.map and Stream.map in a single call chain. But since the usersIds == null case is handled, you don't need Optional.ofNullable anymore. You can simplify this to just operations over your ids and Tenants.

Something like this:

public Set&lt;TenantDTO&gt; getAllTenantsOfUsers(Set&lt;Long&gt; usersIds) {
    if (usersIds == null) {
        return Collections.emptySet();
    }
    return tenantRepository
            .findAll(QTenant.tenant.users.any().id.in(usersIds))
            .stream()
            .map((tenant) -&gt; tenantMapper.toDto(tenant))
            .collect(Collectors.toSet());
}


Now that getAllTenantsOfUsers returns Set(possibly empty Set), all clients of this code can use it directly instead of caring about handling and unwrapping optional.