我有一串单词的流(Stream),这个格式不是由我设置的,也不能更改。例如:
Stream<String> doc1 = Stream.of("how", "are", "you", "doing", "doing", "doing");
Stream<String> doc2 = Stream.of("what", "what", "you", "upto");
Stream<String> doc3 = Stream.of("how", "are", "what", "how");
Stream<Stream<String>> docs = Stream.of(doc1, doc2, doc3);
我想将这个内容转化成 Map<String, Multiset<Integer>>
结构(或其相应的流,因为我想进一步处理),其中键 String
是单词本身,Multiset<Integer>
表示该单词在每个文档中的出现次数(0不应计算在内)。Multiset 是 Google Guava 类(而不是 Java.util.)。例如:
how -> {1, 2} // because it appears once in doc1, twice in doc3 and none in doc2(so doc2's count should not be included)
are -> {1, 1} // once in doc1 and once in doc3
you -> {1, 1} // once in doc1 and once in doc2
doing -> {3} // thrice in doc3, none in others
what -> {2,1} // so on
upto -> {1}
在Java 8中,有什么好的方法可以做到这一点?
我尝试使用flatMap,但内部的Stream极大地限制了我的选择。
.count(Object)
来获取元素出现的次数,这似乎在单词计数本身中并不必要。如果您只需要允许重复的任意顺序的值,则List仍然是最佳解决方案。 - Sean Van Gorder