2017-04-12 42 views
2

我想將字符串轉換爲字典,其中包含作爲鍵的所有唯一單詞以及作爲值的轉換。如何使用Java功能API減少列表以映射

我知道如何將一個字符串轉換爲流含獨特話(Split -> List -> stream() -> distinct()),我有可用的翻譯服務,但什麼是減少流進Map與原始元素最便捷的方式,它的翻譯一般?

+3

我認爲您正在尋找[Collectors.toMap(...)](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap -java.util.function.Function-java.util.function.Function-) –

+1

你可以發佈你的代碼嗎?你試圖做什麼? – freedev

回答

6

您可以直接做到這一點通過收集:

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

這會返回一個Map<String, String>其中地圖關鍵是原始字符串和映射值會轉換。

2

假設你有一個字符串,沒有重複的列表"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,單詞2 = translation2,字1 = translation1}

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}