mel3kings
mel3kings

Reputation: 9415

How to check string against multiple collections using streams

I'm trying generate a specific String with the format: *.*.*.* it could be say QUEUE1.NONE.QUEUE3.NONE. To be specific this is a routing key for my rabbitmq to determine which queue to receive a specific event based on a collection of events, so SET1 would contain events for QUEUE1 etc etc.

The below is what I came up with but I think its too verbose, is there a more efficient way of doing this using streams?

Problem with using flatmap is that I have to return a different value if it is in different set, and flatmap just merges the sets.

return Optional.ofNullable(eventName).map(event->{
      StringBuffer sb = new StringBuffer()
          .append(Optional.of(event).filter(SET1::contains).map(t -> VALUE1).orElse(SKIP)).append(DELIMITER)
          .append(Optional.of(event).filter(SET2::contains).map(t -> VALUE2).orElse(SKIP)).append(DELIMITER)
          .append(Optional.of(event).filter(SET3::contains).map(t -> VALUE3).orElse(SKIP)).append(DELIMITER)
          .append(Optional.of(event).filter(SET4::contains).map(t -> VALUE4).orElse(SKIP));
      return sb.toString();

Upvotes: 2

Views: 277

Answers (1)

Misha
Misha

Reputation: 28183

You are unnecessarily complicating things with the optionals. Why not just keep it simple?

String.join(DELIMITER,
    SET1.contains(event) ? VALUE1 : SKIP,
    SET2.contains(event) ? VALUE2 : SKIP,
    SET3.contains(event) ? VALUE3 : SKIP,
    SET4.contains(event) ? VALUE4 : SKIP
);

Upvotes: 1

Related Questions