I have two result sets (rs1
and rs2
) having same fields. Now how to combine those two result sets into one so that duplicate rows are shown once.
views:
361answers:
2
+5
A:
if the two ResultSet
s are from the same database then why not combine them during the retrieval by using union
; e.g.
select A, B
from C
union
select A, B
from D
However, if this is not an option then I suggest defining a Row
class to represent a Row extracted from your ResultSet
and implementing equals
/ hashCode
to allow the Row
to be compared for equality. Then simply add each Row
to a Set
(e.g. HashSet
) in order to remove duplicates.
Adamski
2010-02-18 16:52:09
+1 ... great answer ... very precise and to the point... I would upvote you 10 times if I had the rights.
Yatendra Goel
2010-02-18 19:13:18
UNION removes duplicates, forcing a sort. UNION ALL functionally concatenates result sets. If dups are acceptable or you know the two result sets have no overlap, use UNION ALL.
Adam Musch
2010-02-18 20:41:12
@Adam: The OP already stated he wanted duplicate rows to only be shown once, hence why I mentioned UNION rather than UNION ALL.
Adamski
2010-02-19 08:45:14
+3
A:
You can:
- Create a class that has properties corresponding to the columns
- implement the
equals()
andhashCode()
methods using the fields by which you define "duplicate" (let your IDE help you with the generation of these) createa a
Set
(HashSet
):Set combinedDataSet = new HashSet();
Iterate each resultSet, and construct objects:
while (rs1.next) { YourClass obj = new YourClass(); obj.setSomeProperty(rs.getString(1)); obj.setAnotherProperty(rs.getString(2)); // etc.. cominbedDataSet.add(obj); }
The same iteration goes for
rs2
Do this only in case you can't get the desired result via an SQL query!
Bozho
2010-02-18 16:54:34
@Bozho I want to communicate with you. I don't have any programming problems which I can post here. You have answered various questions of mine and thus, I know that you are the right person to have advice from you for my career. I checked your blog too but didn't find any way to communicate with you. I don't want to use SO to communicate with you as it would be wrong. I would be very grateful to you if you give me some time from your precious time and tell me how can I chat with you.Thanks.
Yatendra Goel
2010-02-19 13:22:10
@Yatendra Goel if you have particular questions, ask them at SO. If you have less-particular questions, check my blog (linked in my profile here) and drop me a comment.
Bozho
2010-02-19 13:31:51