创建唯一值的 ArrayList [英] Create an ArrayList of unique values

查看:27
本文介绍了创建唯一值的 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList 的值取自一个文件(很多行,这只是一个摘录):

I have an ArrayList with values taken from a file (many lines, this is just an extract):

20/03/2013 23:31:46 6870    6810    6800    6720    6860    6670    6700    6650    6750    6830    34864   34272
20/03/2013 23:31:46 6910    6780    6800    6720    6860    6680    6620    6690    6760    6790    35072   34496

其中每行的前两个值是包含数据并存储在单个元素中的字符串.

Where the first two values per line are strings that contain data and are stored in a single element.

我想要做的是比较字符串数据元素并删除,例如,第二个和该行中引用的所有元素.

What I want to do is compare the string data elements and delete, for example, the second one and all the elements referred to in that line.

现在,我使用了一个 for 循环,它每 13 个元素比较字符串(为了只比较数据字符串).

For now, I've used a for loop that compares the string every 13 elements (in order to compare only data strings).

我的问题:我可以实施其他更好的解决方案吗?

My question: can I implement other better solutions?

这是我的代码:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception{

        //The input file
        Scanner s = new Scanner(new File("prova.txt"));

        //Saving each element of the input file in an arraylist 
        ArrayList<String> list = new ArrayList<String>();
        while (s.hasNext()){
            list.add(s.next());
        }
        s.close();

        //Arraylist to save modified values
        ArrayList<String> ds = new ArrayList<String>();

        //
        int i;
        for(i=0; i<=list.size()-13; i=i+14){

            //combining the first to values to obtain data  
            String str = list.get(i)+" "+list.get(i+1);
            ds.add(str);
            //add all the other values to arraylist ds
            int j;
            for(j=2; j<14; j++){
                ds.add(list.get(i+j));
            }

            //comparing data values
            int k;  
            for(k=0; k<=ds.size()-12; k=k+13){
                ds.get(k); //first data string element  
                //Comparing with other strings and delete
                //TODO  
            }
        }
    }
}

推荐答案

创建唯一值的 Arraylist

Create an Arraylist of unique values

您可以使用 Set.toArray() 方法.

不包含重复元素的集合.更正式地说,集合不包含元素对 e1 和 e2,使得 e1.equals(e2),并且在最多一个空元素.顾名思义,这个接口模型数学集合抽象.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

http://docs.oracle.com/javase/6/docs/api/java/util/Set.html

这篇关于创建唯一值的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆