简体   繁体   中英

comparing 2 ArrayList in Java

I got 2 ArrayList

List fileArray = new ArrayList(); List fileTxt = new ArrayList();

List<String> newDoc = new ArrayList<String>();        

while((fileName = fileRead.readLine()) !=null){
    fileArray.add(fileName);
}
fileRead.close();

while((txtName = txtRead.readLine()) !=null){
    fileTxt.add(txtName);
}
txtRead.close();

I want to compare fileArray data with fileTxt data, but don't know how to do that, because to I'm thinking to compare I need to get the data first. And to do that I need to looping the array and using the .get like

for(int a=0;a<fileTxt.size();a++){
    System.out.println(fileTxt.get(a));
}

I know this is wrong, but anyone can help me.

note: I want to use something like contains method but can't because the data is 5 million rows. (not equals method)

Updated: I want to find a word in fileTxt that appeared in the fileArray. (so basically its like contains)

要比较2个数组列表中的2个值,请执行以下操作:

if(fileArray.get(index).equals(fileTxt.get(index)))

There is a wondefull function.

System.out.println(array1.equals(array2)); 

Then, you might want to check your answer by hands:

    ArrayList like1 = new ArrayList();
    ArrayList like2 = new ArrayList(); 
    ...

    boolean flag = true;
    if (!Math.min(like1.size(), like2.size()) == Math.max(like1.size(), like2.size())) 
    {
        flag = false;
    }
    for (int i = 0; i < Math.min(like1.size(), like2.size()); i++) {
        if (!like1.get(i).equals(like2.get(i))) {
            flag = false;
            break;
        }
    }

You can do this using the removeAll() method.

fileArray.removeAll(fileTxt);
fileTxt.removeAll(fileArray);

If one of them still have data, this means that the two List where different.

But storing 5 millions data in a Java list is not something I will advise you. Perhaps you should think about something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM