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 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.
回答2:
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!