将多集计数转换为列表 Java

Converting Multiset Count into a List Java

有什么方法可以将 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));
    // ...
}

就目前而言,我可以将最常出现的单词输出到 Processing 的控制台中。我想知道是否有可能将相应的单词及其计数添加到数组或列表中。我试过这样:

for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
    float a[] = myMultiset.count(word);
}

但只收到错误,指出我无法将 int 转换为 float[]

这可能吗?我做错了吗?我以前从未使用过 Multisets,所以任何帮助都会非常有用

更新: 我用它来获取最高计数的副本,但无法将其转换为列表。

Multiset<String> sortedList = Multisets.copyHighestCountFirst(myMultiset);

请参阅Multiset.entrySet() docs:

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 个最常发生的 owrd,我将遍历 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 个元素。