Reputation: 37
I know how to do intersection of two files . using hash map or an array list.
In array list using contains method and in hash map combining two hash map suing single for loop
But have a problem in doing my files.
My files have two columns in each. i just want to intersect the 1st columns of both files.
those columns which gets intersect will be store in new file, but i also want to store the 2nd columns of those intersected columns from both the files . can any1 suggest me how to get those two columns of the file.
My file look like this:-
'1' '2,4'
'2' '3,4,5'
'3' '2,3,4'
'5' '3,4,5'
'1,3' '2,4'
'2,3' '3,4'
'2,5' '3,4,5'
'3,5' '3,4'
'2,3,5' '3,4'
The single quotes seperate the two columns.
Upvotes: 0
Views: 1607
Reputation: 27946
If I understand your problem correctly, you're asking how to find the intersection of two lists while maintaining the reference to the equivalent data in a second list. You have a lot of information about the format of the file but you haven't asked any questions about reading the file so I'm going to assume you're ok with that. If not then I suggest you ask a separate question about reading files in your format.
Firstly, given each row in your files seems to represent a single record you should create a class to represent that record with the two 'columns' of data represented as instance variables. You will need methods to compare and print your records. I'm ignoring constructors etc.
class Record {
private final String value1;
private final String value2;
public boolean value1_Equals(Record other) {
return this.value1.equals(other.value1);
}
public void printTo(OutputStream out) {
...
}
}
Secondly, read your two files of data into two lists of records:
List<Record> records1;
List<Record> records2;
Thirdly, create a new list that is the intersection of those two. Here's an example using Java 8 streams; if you don't have Java 8 add a comment and I'll give an equivalent in Java 7 (though from your question it seems you know how to do this already):
List<Record> intersection = records1.stream()
.filter(record -> record2.stream().anyMatch(record::value1_Equals))
.collect(Collectors.toList());
Finally, print the intersection in a new list:
intersection.forEach(record -> record.printTo(file));
An equivalent version that does not use streams might be:
List<Record> intersection = new ArrayList(records1);
intersection.retainAll(records2);
for (Record record: intersection)
record.printTo(file);
Upvotes: 1