如何使用Java功能API减少要映射的列表

时间:2017-04-12 08:24:30

标签: java functional-programming java-8 java-stream

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

我知道如何将String转换为包含唯一字(Split -> List -> stream() -> distinct()),并且我提供了翻译服务,但是将流简化为{{{}的最简便方法是什么? 1}}与原始元素及其一般的翻译?

3 个答案:

答案 0 :(得分:8)

您可以通过收集直接执行此操作:

yourDistinctStringStream
.collect(Collectors.toMap(
    Function.identity(), yourTranslatorService::translate
);

这将返回Map<String, String>,其中地图键是原始字符串,地图值将是翻译。

答案 1 :(得分:3)

假设您有一个没有重复的字符串"word1", "word2", "workdN"列表:

这应解决问题

List<String> list = Arrays.asList("word1", "word2", "workdN);

Map<String, String> collect = list.stream()
   .collect(Collectors.toMap(s -> s, s -> translationService(s)));

这将返回,不保持插入顺序。

  

{wordN = translationN,word2 = translation2,word1 = translation1}

答案 2 :(得分:0)

请尝试以下代码:

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}