You can use the HashMap<K,V> where K: a[i] and V: k-a[i] This may result in an incorrect answer if there are duplicates in an array.
Say for instances:
int a[] = {4, 4, 4, 4, 4, 4, 4, 4, 4} where k = 8 or:
int a[] = {1, 3, 3, 3, 3, 1, 2, 1, 2} where k = 4.
So in order to avoid that, we can have a List<List<Integer>> , which can check each pair and see if it is already in the list.
static int numberOfPairs(int[] a, int k) { List<List<Integer>> res = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); for(int element:a) { List<Integer> list = new ArrayList<>(); if(map.containsKey(element)) { list.add(element); list.add(map.get(element)); if(!res.contains(list)) res.add(list); } else map.put(k - element, element); } return res.size(); }