Created
November 27, 2012 09:23
-
-
Save endymuhardin/4153298 to your computer and use it in GitHub Desktop.
Cara union dua hasil query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DtoSaya { | |
private String tanggal; | |
private Integer yes; | |
private Integer no; | |
// getter setter | |
} | |
// nantinya ini hasil query database | |
Map<String, DtoSaya> query1 = new HashMap<String, DtoSaya>(); | |
Map<String, DtoSaya> query2 = new HashMap<String, DtoSaya>(); | |
// sebagai contoh, datanya dihardcode | |
DtoSaya row1 = new DtoSaya(); | |
row1.setTanggal("2012-11-22"); | |
row1.setYes(0); | |
row1.setNo(1); | |
query1.put(row1.getTanggal(), row1); | |
DtoSaya row2 = new DtoSaya(); | |
row2.setTanggal("2012-11-26"); | |
row2.setYes(0); | |
row2.setNo(1); | |
query1.put(row2.getTanggal(), row2); | |
DtoSaya row3 = new DtoSaya(); | |
row3.setTanggal("2012-11-26"); | |
row3.setYes(0); | |
row3.setNo(1); | |
query2.put(row3.getTanggal(), row2); | |
// menggabungkan query1 dan query2 | |
Map<String, DtoSaya> hasilUnion = new HashMap<String, DtoSaya>(); | |
// masukkan dulu semua hasil query 1 | |
hasilUnion.addAll(query1); | |
for(String key1 : hasilUnion.keySet()){ | |
for(String key2 : query2.keySet()){ | |
DtoSaya d = hasilUnion.get(key2); // ini yang sudah ada | |
DtoSaya d2 = query2.get(key2); | |
if(d == null){ // belum ada tanggal yang sama, langsung aja put | |
hasilUnion.put(d2.getTanggal(), d2); | |
} else { // ada tanggal yang udah tersimpan, harus disum | |
d.setYes(d.getYes() + d2.getYes()); | |
d.setYes(d.getNo() + d2.getNo()); | |
hasilUnion.put(d.getTanggal(), d); | |
} | |
} | |
} | |
return hasilUnion; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment