Is there better alternative to making an optional set of elements from iterable in java?
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.