如何使用Java函数式API将列表转换为映射表

9

我想将一个文本字符串转换为字典,其中包含所有唯一单词作为键,翻译作为值。

我知道如何将字符串转换为包含唯一单词的流 (Split -> List -> stream() -> distinct()),并且我有可用的翻译服务,但是将流缩减为Map与原始元素及其翻译的最方便方法是什么?


3
我认为你正在寻找Collectors.toMap(...) - Robin Topper
1
你能否请发一下你的代码?你尝试了什么? - freedev
3个回答

12
您可以直接通过collect实现:
yourDistinctStringStream
.collect(Collectors.toMap(
    Function.identity(), yourTranslatorService::translate
);

这将返回一个 Map<String, String>,其中map的键是原始字符串,而map的值将是翻译后的字符串。


5
假设您有一个没有重复的字符串列表“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}


1

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}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接