从bbs中看到的问题:从大量数据中取top100,整理的思路
程序员文章站
2022-07-14 13:55:45
...
TreeSet算法很强悍,以后一定要记得使用
package com; import java.util.Iterator; import java.util.Random; import java.util.TreeSet; import com.wfy.util.TimeUtil; import sun.reflect.generics.tree.Tree; public class TestMain { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Random rd = new Random(); int rb = 1024*1024; int a = 100000000; int[] test = new int[a]; for (int i = 0; i < a; i++) { test[i] = rd.nextInt(); } TreeSet<Integer> tree = new TreeSet<Integer>(); System.out.println("开始:"+TimeUtil.dateTime1()); for (int i = 0; i < a; i++) { if(tree.size()<100){ tree.add(test[i]); }else{ if( tree.first() < test[i] ){ tree.remove( tree.first() ); tree.add( test[i] ); } } } System.out.println("结束:"+TimeUtil.dateTime1()); Iterator<Integer> iterator = tree.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }