Java深入---百萬數據提取最大的前一百個數據

package BigData;

import java.io.*;
import java.util.PriorityQueue;
import java.util.Queue;

public class FileTest {
	public FileTest() {
	}

	public static void main(String[] args) {
		// madeData();
		sortData();
	}

	private static void sortData() {
		FileReader fr = null;
		BufferedReader br = null;
		Queue<Integer> priorityQueue = new PriorityQueue<Integer>(100);
		try {
			fr = new FileReader("F:/add3.txt");
			br = new BufferedReader(fr);
			int temp;
			int temp1;
			String str = null;
			long begin3 = System.currentTimeMillis();
			while ((str = br.readLine()) != null) {
				temp = Integer.valueOf(str);
				if (priorityQueue.size() < 100) {
					priorityQueue.add(temp);
				} else {
					temp1 = priorityQueue.poll();
					if (temp1 < temp) {						
						priorityQueue.offer(temp);
					}else{
						priorityQueue.offer(temp1);
					}
				}
				System.out.println("FileReader執行耗時:" + priorityQueue.toString());
			}
			br.close();
			fr.close();
			long end3 = System.currentTimeMillis();
			System.out.println("FileReader執行耗時:" + (end3 - begin3) + " 豪秒");
			System.out.println("FileReader執行耗時:" + priorityQueue.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	private static void madeData() {
		FileWriter fw = null;
		int count = 1000000;// 寫文件行數
		try {
			fw = new FileWriter("F:/add3.txt");
			int temp = (int) (Math.random() * 1000000);
			long begin3 = System.currentTimeMillis();
			for (int i = 0; i < count; i++) {
				temp = (int) (Math.random() * 1000000);
				fw.write(temp + "\r\n");
			}
			fw.close();
			long end3 = System.currentTimeMillis();
			System.out.println("FileWriter執行耗時:" + (end3 - begin3) + " 豪秒");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}
維護一個堆,然後向裏面添加數據。。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章