有 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));
    // ...
}

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

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

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

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

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

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

共 (1) 个答案

  1. # 1 楼答案

    请参阅^{} 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个最常出现的单词及其频率。如果您只需要单词,只需使用^{}方法:

    ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);
    
    ImmutableList<String> list = top.asList();
    

    并在list上迭代以获得前5个元素