David
David

Reputation: 321

Iterate two maps using stream

I have two maps with the same size but the type of their values are different. Now I need to iterate them and generate new map. I tried stream but the Map.Entry cannot be resolved. I'm using JDK 11;

Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets = getConsumerGroupOffsets(groupId);
Map<TopicPartition, Long> topicEndOffsets = getTopicEndOffsets(groupId, consumerGroupOffsets.keySet());
Map<Object, Object> consumerGroupLag = consumerGroupOffsets.entrySet().stream()
                    .map(entry -> mapEntry(entry.getKey(), new OffsetAndLag(topicEndOffsets.get(entry.getKey()), entry.getValue().offset())))

Upvotes: 0

Views: 441

Answers (1)

WJS
WJS

Reputation: 40034

It's a little confusing where the lag is coming from since it appears you are retrieving offsets only.

But this is how it would be structured to get the long values regardless of what they are called (I guessed at the constructor for the OffsetAndLag class)

Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets = ...;
Map<TopicPartition, Long> topicEndOffsets = ...;
  • Use the key from consumerGroupOffsets for the target key.
  • use that key to retrieve the lag (or offset) from topicEndOffsets
  • use the value for that key (which should be OffsetAndMetadata) to get the offset (or lag)
Map<TopicPartition, OffsetAndLag> consumerGroupLag =
        consumerGroupOffsets.entrySet().stream()
                .collect(Collectors.toMap(Entry::getKey,
                        entry -> new OffsetAndLag(
                                topicEndOffsets
                                        .get(entry.getKey()),
                                entry.getValue().offset())));

Expected OffsetAndLag class (or something similar)

static class OffsetAndLag {
    public long offset;
    public long lag;
    public OffsetAndLag(long offset, long lag) {
        this.offset = offset;
        this.lag = lag;
    }
}

Upvotes: 1

Related Questions