【问题标题】:Reduce/Collect `List<Map<String, Set<String>` to `Map<String, Set<String>>`减少/收集 `List<Map<String, Set<String>` 到 `Map<String, Set<String>>`
【发布时间】:2019-08-26 21:14:36
【问题描述】:

List 上执行parallelStream() 后,我最终得到List&lt;Map&lt;String, Set&lt;String&gt;。我想将其统一为Map&lt;String, Set&lt;String&gt;&gt;(它只会在Maps 的List 中保持唯一性)。

我不熟悉collectreduce 函数,所以没有什么可继续的。

现有代码:

private val TYPES = listOf("string", "integer")

private fun getLinesOfEachTypeAcrossMultipleFiles(files: List<File>): Map<String, Set<String>> {
  return files
    .parallelStream()
    .map { file ->
      TYPES.associate {
        it to getRelevantTypeLinesFromFile(file)
      }
    }
// Converted into a Stream<String, Set<String>>
// .reduce() / collect() ?
}

private fun getRelevantTypeLinesFromFile(it: File): Set<String> {
  // Sample code
  return setOf()
}

【问题讨论】:

    标签: kotlin java-stream reduce collect


    【解决方案1】:

    我想出并实现了一个使用 fold 运算符(而不是 reducecollect)的 Kotlin 特定解决方案:

    private val TYPES = listOf("string", "integer")
    
    private fun getLinesOfEachTypeAcrossMultipleFiles(files: List<File>): Map<String, Set<String>> {
      return files
        .map { file ->
          TYPES.associate { it to getRelevantTypeLinesFromFile(file) }
        }
    
        .fold(mutableMapOf<String, MutableSet<String>>()) { acc, map ->
          acc.apply {
            map.forEach { key, value ->
              acc.getOrPut(key) { mutableSetOf() }.addAll(value)
            }
          }
        }
    }
    
    private fun getRelevantTypeLinesFromFile(it: File): Set<String> {
      // Sample code
      return setOf()
    }
    

    使用fold 的一个好处是我们不需要将数据类型从Map 更改为MutableMapSet 更改为MutableSet

    【讨论】:

      【解决方案2】:

      如果您正在寻找等效的 Java 代码,您可以使用 flatMap 流式传输所有条目,然后将它们收集为具有合并功能的 Map:

      Map<String, Set<String>> some(List<Map<String, Set<String>>> listOfMap) {
          return listOfMap.stream()
                  .flatMap(a -> a.entrySet().stream())
                  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                          (s1, s2) -> {
                              s1.addAll(s2);
                              return s1;
                          }));
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 2015-11-17
        • 1970-01-01
        相关资源
        最近更新 更多