background
create series of sql join statements using 2 operands: primary , secondary. generic form of join statement is:
join primary primary on (secondary.id == primary.id) problem
the code iterates on list of primary , secondary operands, follows:
for( bundle primaryoperand : bundlecomparators ) { for( bundle secondaryoperand : sortedbundles ) { the problem nested loop generates following:
join primary primary on (secondary.id == primary.id) join secondary secondary on (primary.id == secondary.id) the second join superfluous and, in case, causes error. duplication can eliminated following hypothetical data structure:
if( !interchangeablemap.contains( primaryoperand, secondaryoperand ) ) { interchangeablemap.put( primaryoperand, secondaryoperand ); outputjoin( primaryoperand, secondaryoperand ); } where interchangeablemap.contains(...) return true if primaryoperand mapped secondaryoperand or secondaryoperand mapped primaryoperand.
questions
- does such data structure exist in java libraries?
- if not, data structures use implementation?
ideas
my first thought create class contains 2 hashmaps. checking containment queries 2 hashmaps see if 1 map contains primary , secondary operands or other map contains secondary , primary operands. insertions put 2 operand combinations respective hashmaps.
thank you!
here solution based on @roland's suggestion:
public final class pair { private final object a; private final object b; public pair(object a, object b) { this.a = a; this.b = b; } @override public boolean equals(object o) { if(o == null || !(o instanceof pair)) return false; pair = (pair) o; return this.a.equals(that.a) && this.b.equals(that.b) || this.a.equals(that.b) && this.b.equals(that.a); } @override public int hashcode() { return a.hashcode() ^ b.hashcode(); } } then:
set<pair> set = new hashset<pair>(); for(bundle primaryoperand : bundlecomparators) { for(bundle secondaryoperand : sortedbundles) { pair p = new pair(primaryoperand.id, secondaryoperand.id); if(set.contains(p)) continue; set.add(p); outputjoin(primaryoperand, secondaryoperand); } } a subtle point solution: must override hashcode() method (hash value must reflect equality relation), must in symmetric way, is: hash value of <a,b> must == of <b,a>
Comments
Post a Comment