0

After performing a parallelStream() on a List, I end up with a List<Map<String, Set<String>. I want to unify this into a Map<String, Set<String>> (which will only keep uniques across the List of Maps).

I am unfamiliar with the collect and reduce functions, so don't have anything to go ahead with.

Existing code:

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

2 Answers 2

1

If you're looking for an equivalent Java code, you can stream all the entries using flatMap and then collect them as a Map with a merge function as :

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;
                    }));
}
Sign up to request clarification or add additional context in comments.

Comments

0

I figured out and implemented a Kotlin-specific solution of using the fold operator (instead of reduce or collect):

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

A benefit of using fold is that we don't need to change the type of the data from Map to MutableMap and Set to MutableSet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.