我想将字符串转换为字典,其中包含作为键的所有唯一单词以及作为值的转换。如何使用Java功能API减少列表以映射
我知道如何将一个字符串转换为流含独特话(Split -> List -> stream() -> distinct())
,我有可用的翻译服务,但什么是减少流进Map
与原始元素最便捷的方式,它的翻译一般?
我想将字符串转换为字典,其中包含作为键的所有唯一单词以及作为值的转换。如何使用Java功能API减少列表以映射
我知道如何将一个字符串转换为流含独特话(Split -> List -> stream() -> distinct())
,我有可用的翻译服务,但什么是减少流进Map
与原始元素最便捷的方式,它的翻译一般?
您可以直接做到这一点通过收集:
yourDistinctStringStream
.collect(Collectors.toMap(
Function.identity(), yourTranslatorService::translate
);
这会返回一个Map<String, String>
其中地图关键是原始字符串和映射值会转换。
假设你有一个字符串,没有重复的列表"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}
试试下面的代码:
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}
我认为您正在寻找[Collectors.toMap(...)](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap -java.util.function.Function-java.util.function.Function-) –
你可以发布你的代码吗?你试图做什么? – freedev