How to combine two ResultSets in Java?

2019-06-19 21:05发布

问题:

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.

回答1:

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.



回答2:

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!



标签: java jdbc