Tuo*_*nen 5 java functional-programming java-8 java-stream
我想将一串文本转换为字典,其中包含所有唯一的单词作为键,并将翻译作为值.
我知道如何将String转换为包含唯一单词的流(Split -> List -> stream() -> distinct()),并且我有可用的翻译服务,但是最简单的方法是将流缩减为Map原始元素并将其翻译为一般?
小智 10
你可以通过收集直接做到这一点:
yourDistinctStringStream
.collect(Collectors.toMap(
Function.identity(), yourTranslatorService::translate
);
Run Code Online (Sandbox Code Playgroud)
这将返回Map<String, String>地图键是原始字符串的位置,而地图值将是翻译.
假设您有一个"word1", "word2", "wordN"没有重复的字符串列表:
这应该可以解决问题
List<String> list = Arrays.asList("word1", "word2", "workdN");
Map<String, String> collect = list.stream()
.collect(Collectors.toMap(s -> s, s -> translationService(s)));
Run Code Online (Sandbox Code Playgroud)
这将返回,不维护插入顺序。
{wordN=translationN, word2=translation2, word1=translation1}
| 归档时间: |
|
| 查看次数: |
1612 次 |
| 最近记录: |