Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - 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())))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...