通过迭代计算

时间:2014-03-11 04:49:13

标签: java count set

Sunny Hot High False No
Overcast Hot High False Yes
Rainy Mild High False Yes

这是天气数据集的示例。

I need to get the count of the class label without storing them to list,array etc

在阅读该行时,我应该能够获得NOYES计数。比较不能是jst no和yes。它可以是任意数量的类,如iris数据集。

为了获得unique class label我使用的设置

Set<String> set = new HashSet<String>();
String classLabel = keys.substring(keys.lastIndexOf(" ") + 1);
set.add(classLabel);

那么如何获得每个课堂标签的计数?

1 个答案:

答案 0 :(得分:0)

您的问题确实缺少一些信息,我的答案是做了很多假设,特别是因为您将classLabel放在Set中,我假设您也可以使用其他类型的集合,在本例中为Map

private static void weatherForecast() {

    String[] keys = {"Sunny Hot High False No", 
                     "Overcast Hot High False Yes", 
                     "Rainy Mild High False Yes"};

    Map<String, Integer> map = new HashMap<String, Integer>();

    for (String key : keys) {
        String[] split = key.split(" ");
        //Assume your data set is consistent with the 'classLabel' 
        //always the last field.
        String classLabel = split[split.length-1];

        if (map.containsKey(classLabel)) {
            map.put(classLabel, map.get(classLabel) + 1);
        } else {
            map.put(classLabel, 1);
        }
    }

    for (String string : map.keySet()) {
        System.out.println(string + ": " + map.get(string));
    }    
}