求助求助!
我有一个txt 文件 文件里每一行只有两个数字
12 14
12 15
13 16
13 29
13 30
等等要求找出每一行第一个比如是12  他之后的所有第二个数字的集合
比如输出结果为
12:14,15,16
13:16,29,30请问怎么存到arraylist里面
另外算法要求是在线性时间里完成
txt文件非常之大

解决方案 »

  1.   

    先用BufferedReder按行读取,以空格分成两个数字
    用Map<Integer,ArrayList<Integer>的形式存放
    ArrayList<Integer> list = map.get(12);
    if(list == null)
    {
       list = new ArrayList<Integer>();
    }
    list.add(14);//
      

  2.   

    不知道你所谓的“文件非常之大”有多大,而且需要在线性时间完成,不知道多线程可不可以;正常实现可以如下代码:
    try {
    FileReader fr = new FileReader("C:\\Users\\chenxh\\Desktop\\测试数据.txt");
    BufferedReader bf = new BufferedReader(fr);
    String str = null;
    Map map = new HashMap<String, ArrayList>();
    List list = null;
    while((str=bf.readLine()) != null){
    String[] strs = str.split(" ");
    Object obj =  map.get(strs[0]);
    if(obj == null)
    list = new ArrayList();
    else
    list = (List)obj;
    list.add(strs[1]);
    map.put(strs[0], list);
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    这类读写应该很快的,只不过文件越大可能消耗内存更大些,你可以试试。如果不能实现,需要优化怎么实现,同求解
      

  3.   

    非常之大就是这个txt有24个G
    要在hadoop上跑。。
    还没跑你的程序 认真学习先
      

  4.   


    public static void analysisFile(String srcPath, String dstPath)
    throws IOException {
    BufferedReader in = null;
    try {
    in = new BufferedReader(new FileReader(srcPath));
    PrintWriter out = null;
    try {
    out = new PrintWriter(dstPath);
    analysisStream(in, out);
    } finally {
    if (out != null) {
    out.close();
    out = null;
    }
    }
    } finally {
    if (in != null) {
    in.close();
    in = null;
    }
    }
    } /**
     * 数据都有序排列,未作第2列的重复数据验证
     */
    private static void analysisStream(BufferedReader in, PrintWriter out)
    throws IOException {
    String read = null;
    String temp = null;
    while ((read = in.readLine()) != null) {
    if (read.trim().length() == 0) {
    continue;
    } int index = read.indexOf(' '); // 文件较大,效率上不采用split
    if (index == -1) {
    throw new IllegalArgumentException("Error Data:" + read);
    } String num1 = read.substring(0, index).trim();
    String num2 = read.substring(index + 1, read.length()).trim();
    if (num1.equals(temp)) {
    out.print(',' + num2);
    } else {
    if (temp != null) {
    out.println();
    }
    out.print(num1 + ':' + num2);
    }
    out.flush();
    temp = num1;
    }
    }可以保证任何大小的数据皆能运行...
      

  5.   

    如果采用arraylist存储,肯定会内存溢出...
      

  6.   

    我按着2楼的方法确实可以输出来 再问个问题  譬如之前找的都是每行第二个数
    12 13
    12 14
    12 16
    13 12
    13 16现在想让他输出为:
    12:13,14,15;13
    13,:12,16;12
    15:null;12,16
    16:null;13
    就是分号之后的数字是当前这个key 跟着哪一个数字这个怎么解决呀??
      

  7.   

    楼主的意思是后面的“value”也成为“key”?15,16的结果怎么出来的?如果我理解的没错,楼主转一下弯子就完事了嘛。读取一行,分别用两个数字作为key来查询,之后保存就行了。不过楼主的24G文件能正常读取?
      

  8.   

    既然都hadoop了那就mapreduce跑啊, 把第一个数字取出来当key 发给reduce。然后迭代reduce收到的数据组合成想要的输出就ok了。。不管24g还是2t都能跑。