有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在整数文件中查找最频繁的元素

我正在编写一个程序,以查找文本文件中最常见的元素。到目前为止,我已经将该文件读入一个列表,然后遍历该列表,找到每个值的出现点,并将它们映射到一个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) 个答案

  1. # 1 楼答案

    你应该查一下Java Documentation for TreeMap。它的设计目的是不存储重复的键,因此,由于您正在按键的频率进行排序,因此具有相同频率的值将在地图中被覆盖