I was given a problem - there is a box containing label and has value in it. for example - box with label 'a' contains value 2, box with label 'b' contains value 7 etc. I was asked to find the pairs that adds to sum 10. I wrote below code to find the pair using hashmap. But it contains same result twice with only difference of position of letter. For example - (a,e) is same as (e,a) How can I keep/print only the unique pair?
Below is my code :
public class BoxValue {
public void pair()
{
int sum = 10;
HashMap<Integer, Character> m = new HashMap<Integer, Character>();
m.put(2, 'a');
m.put(7, 'b');
m.put(4, 'c');
m.put(3, 'd');
m.put(8, 'e');
m.put(6, 'f');
Set<Integer> s = m.keySet();
for(Integer in : s)
{
if(m.containsKey(sum-in))
System.out.println(m.get(in)+","+m.get(sum-in));
}
}
public static void main(String[] args) {
BoxValue bv = new BoxValue();
bv.pair();
}
}