在整数文件中查找最常用的元素

时间:2017-11-15 23:39:47

标签: java

我正在开发一个程序来查找文本文件中最常用的元素。到目前为止,我已将文件读入List,然后遍历列表以查找每个值的出现并将它们映射到SortedMap。

问题出现在文件中,每个数字均等地出现。我的地图没有填写所有数据,最后只包含一个数字。

这是我的代码:

public class FileAnalyzer {
public static void main(String[] args) throws IOException, FileNotFoundException {

    System.out.print("Please Enter A File Name: ");
    String file = new Scanner(System.in).nextLine();

    final long startTime = System.currentTimeMillis();

    BufferedReader reader = new BufferedReader(new FileReader(file));
    List<Integer> numbers = new ArrayList<>();
    SortedMap<Integer, Integer> sortedMap = new TreeMap<>();    
    String line;

    while ((line = reader.readLine()) != null) {
        numbers.add(Integer.parseInt(line));
    }

    Collections.sort(numbers);

    int frequency = 0;
    int tempNum = 0;

    for (int i = 0; i < numbers.size(); i++) {
        if (tempNum == numbers.get(i)) {
            frequency++;
        } else {
            if (frequency != 0) {
                sortedMap.put((frequency+1), tempNum);
            }
            frequency = 0;
            tempNum = numbers.get(i);
        }
    }
     if (frequency !=0) {
        sortedMap.put((frequency+1), tempNum);
    }

    final long duration = System.currentTimeMillis() - startTime;

        System.out.println(sortedMap);      
        System.out.println("Runtime: " + duration + " ms\n");       
        System.out.println("Least Frequent Digit(s): " + sortedMap.get(sortedMap.firstKey()) + "\nOccurences: " + sortedMap.firstKey());        
    }
}

这也是我在阅读时遇到问题的文本文件:

1
2
1
1
2
1
1
2
1
2
2
2

提前致谢!

1 个答案:

答案 0 :(得分:0)

你应该查看Java Documentation for TreeMap。它被设计为不存储重复键,因此,由于您将频率作为键进行排序,因此地图中将覆盖具有相同频率的值!