Reputation: 155
I want to compare 2 files and check that the contents are equals. But the problem is the data in the files are not in the same order. the equals() method returns me false even if the contents are equal when the elements are not placed in the same order. How can I compare these files in java by ignoring the order ? Best regards!
Upvotes: 2
Views: 2138
Reputation: 5423
Here is the code u want:
Scanner input1= new Scanner(new File("C:/file1.txt");
Scanner input2= new Scanner(new File("C:/file2.txt");
String one= input1.nextLine();//assuming files contain only one line
String two= input2.nextLine();//assuming files contain only one line
Set<String> set1 = new HashSet<String>(Arrays.asList(one.split(";"));
Set<String> set2 = new HashSet<String>(Arrays.asList(two.split(";"));
System.out.println(set1.equals(set2));
Upvotes: 3
Reputation: 533820
Add all the elements to sets and compare the sets. Note: sets will ignore duplicates.
Or you can sort all the elements and compare the results. How you sort them doesn't matter provided the sorting it consistent. i.e. the original order doesn't change the result. Use this if there are duplicates.
Upvotes: 1