I have a Set<Client>
which I am filling with results from a database query. The resulting rows contain different values for clients so that several rows contain values to be added to a single instance of Client
.
The Client
s are stored in the mentioned Set<Client>
and currently, I am checking if the client is already present in that Set
or needs to be created by the following stream:
Set<Client> clients = new TreeSet<>();
// yes, Client implements Comparable<Client>, has hashCode() and equals()
// some things that are irrelevant to this question happen here
// then iterating the database result
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int clientNumber = rs.getInt(...);
String clientName = rs.getString(...);
// get the client from the collection or create a new one if it isn't there
Client client = clients.stream()
.filter(c -> c.getNumber() == clientNumber)
.findFirst()
.orElse(new Client(clientNumber, clientName));
// here I have to check again if the client is in the Set, how can I avoid that?
}
However, this does — of course — not add a possibly newly created Client
to the Set<Client>
, I need to check again if clients
contains this instance afterwards in order to find out if I have to add this instance to clients
or not. I couldn't even try anthing because I couldn't even add methods of Stream
, like concat(...)
at any position in the clients.stream()...
statement.
That leads to the following question:
Is there any way at all that provides a possibility of directly adding a new instance of Client
(or any object) to the Set
while streaming this Set
and the new instance is created by .orElse(new ...)
?
I can imagine something like orElseAdd(new ...)
but couldn't find anything similar.