有什么方法可以将Multiset
中的计数提取到列表中吗?
String[] data = loadStrings("data/data.txt");
Multiset<String> myMultiset = ImmutableMultiset.copyOf(data);
for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
System.out.println(word + ": " + myMultiset.count(word));
// ...
}
就目前情况而言,我可以将最常出现的单词输出到处理中的控制台中。我想知道是否有可能将相应的单词及其计数添加到数组或列表中。我试过这样:
for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
float a[] = myMultiset.count(word);
}
但只收到错误,指出我无法将 int
转换为 float[]
这可能吗?难道我的做法全错了?我以前从未使用过Multiset
,所以任何帮助都会非常有用
更新: 我已使用它来获取最高计数的副本,但无法将其转换为列表。
Multiset<String> sortedList = Multisets.copyHighestCountFirst(myMultiset);
最佳答案
Returns a view of the contents of this multiset, grouped into Multiset.Entry instances, each providing an element of the multiset and the count of that element.
因此,即为了获取出现次数最多的前 5 个单词,我将循环遍历 entrySet()
:
ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);
Iterator<Multiset.Entry<String>> it = top.entrySet().iterator();
for (int i = 0; (i < 5) && it.hasNext(); i++) {
Multiset.Entry<String> entry = it.next();
String word = entry.getElement();
int count = entry.getCount();
// do something fancy with word and count...
}
我假设您需要显示出现次数最多的 5 个单词及其频率。如果您只需要单词,只需使用 asList()
方法:
ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);
ImmutableList<String> list = top.asList();
并迭代list
以获取前5个元素。
关于java - 将多重集计数转换为列表 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269408/