let's continue :-)
sequence
filter
, map
and flatmap
are implemented in roughly the same way:
- create a new List
- perform operations
- Store results in the new list
- return the new list.
this means that for every filter
, map
and flatmap
a new list is created and all the elements are iterated. To increase performance, you can change it into a Sequence.
val message = dictionary.asSequence()
.filter { it.length == word.size }
.filter { it.toSortedCharArray() contentEquals word }
.joinToString(separator = " ")
repeated code
If you look at the code, you see that you get sortedCharArrays from both files.
You can therefor create a function:
fun File.readSortedCharArrays() = readLines().map(String::toSortedCharArray)
so you get
val dictionary = File("dict.txt").getSortedCharArrays()
File("wordList.txt").getSortedCharArrays().forEach { word ->
val message = dictionary.asSequence()
.filter(CharArray::size::equals)
.filter { it contentEquals word }
.joinToString(separator = " ")
println(message)
}
joinTo
finally, joinToString
is a wrapper around a function that takes more arguments: joinTo
. Here you can specify where you like to add the created string to. In our case it is System.out.
altogether
fun String.toSortedCharArray() = toCharArray().apply(CharArray::sort)
fun File.getSortedCharArrays() = readLines().map(String::toSortedCharArray)
val dictionary = File("dict.txt").getSortedCharArrays()
File("wordList.txt").getSortedCharArrays().forEach { word ->
dictionary.asSequence()
.filter(CharArray::size::equals)
.filter { it contentEquals word }
.joinTo(System.out, " ")
}
I know, it looks less beautiful, but it is better code...
Ps, if you want to have it as a list of Strings, instead of printing it out, you need to use flatmap:
fun String.toSortedCharArray() = toCharArray().apply(CharArray::sort)
fun File.getSortedCharArrays() = readLines().map(String::toSortedCharArray)
val dictionary = File("dict.txt").getSortedCharArrays()
val result : List<String> = File("wordList.txt").getSortedCharArrays().flatMap{ word ->
dictionary.asSequence()
.filter { it.size == word.size }
.filter { it contentEquals word }
.toList()
}.map(Any::toString)