tags:

views:

361

answers:

2

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.

+5  A: 

if the two ResultSets 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
+1 ... great answer ... very precise and to the point... I would upvote you 10 times if I had the rights.
Yatendra Goel
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
@Adam: The OP already stated he wanted duplicate rows to only be shown once, hence why I mentioned UNION rather than UNION ALL.
Adamski
+3  A: 

You can:

  1. Create a class that has properties corresponding to the columns
  2. implement the equals() and hashCode() methods using the fields by which you define "duplicate" (let your IDE help you with the generation of these)
  3. createa a Set (HashSet):

    Set combinedDataSet = new HashSet();

  4. 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
+1 ... .......... :)
Yatendra Goel
@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
@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