我想将一个文本字符串转换为字典,其中包含所有唯一单词作为键,翻译作为值。
我知道如何将字符串转换为包含唯一单词的流 (Split -> List -> stream() -> distinct())
,并且我有可用的翻译服务,但是将流缩减为Map
与原始元素及其翻译的最方便方法是什么?
我想将一个文本字符串转换为字典,其中包含所有唯一单词作为键,翻译作为值。
我知道如何将字符串转换为包含唯一单词的流 (Split -> List -> stream() -> distinct())
,并且我有可用的翻译服务,但是将流缩减为Map
与原始元素及其翻译的最方便方法是什么?
yourDistinctStringStream
.collect(Collectors.toMap(
Function.identity(), yourTranslatorService::translate
);
这将返回一个 Map<String, String>
,其中map的键是原始字符串,而map的值将是翻译后的字符串。
“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)));
这将返回,插入顺序不保留。
{word1=translation1, word2=translation2, wordN=translationN}
Try the following code:
public static void main(String[] args) {
String text = "hello world java stream stream";
Map<String, String> result = new HashSet<String>(Arrays.asList(text.split(" "))).stream().collect(Collectors.toMap(word -> word, word -> translate(word)));
System.out.println(result);
}
private static String translate(String word) {
return "T-" + word;
}
会给你输出:
{java=T-java, world=T-world, stream=T-stream, hello=T-hello}