public static <T> Map<String, T> groupPartitionsByTopic(
        Collection<TopicPartition> partitions,
        Function<String, T> buildGroup,
        BiConsumer<T, Integer> addToGroup
    ) {
        Map<String, T> dataByTopic = new HashMap<>();
        for (TopicPartition tp : partitions) {
            String topic = tp.topic();
            T topicData = dataByTopic.computeIfAbsent(topic, buildGroup);
            addToGroup.accept(topicData, tp.partition());
        }
        return dataByTopic;
    }
Group a collection of partitions by topic

@return The map used to group the partitions
clients/src/main/java/org/apache/kafka/common/utils/CollectionUtils.java