Finding pairs of numbers with a given difference Without changing the outputs or the inputs of the method, how would you make this code more readable ?

I am interested in any general improvement it can be made in terms of readability without WORSEN the time complexity.

Above all I'm interested of know if there is a way of doing all this steps in one line:


check if the key exist in the map.
if exist create a list with two elements (pair) and then append the
pair to list of pairs that will be the result.
if not exist do nothing.


Also is there a more elegant way to return array[][] from an ArrayList&lt;ArrayList&lt;Integer&gt;&gt; ?

static int[][] findPairsWithGivenDifference(int[] arr, int k) {

    int n = arr.length; 
    Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(); 

    ArrayList&lt;ArrayList&lt;Integer&gt;&gt; all = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();  

    for (int i = 0; i &lt; n; i++){ 
      map.put(arr[i]-k,arr[i]);
    }

    for (int i = 0; i &lt; n; i++){ 
      int x = arr[i];
      if (map.get(arr[i]) != null) {
        int y = map.get(x);
        ArrayList&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;();
        al.add(y);
        al.add(x);
        all.add(al);
      }
    }

    int m = all.size();
    int[][] res = new int[m][2];

    for (int i = 0; i &lt; m; i++) {
      for (int j = 0; j &lt; 2; j++) {
        res[i][j] = all.get(i).get(j);
      }
    }

  return res;
}
You don't need to use a map here. A set will work just as well, since you can recreate the original value by adding the difference again.

I'm not sure if it's possible to do it in one line (which of course is not necessarily the most readable solution), but you can get close by converting the input array into a set and then using streams:

static int[][] findPairsWithGivenDifference(final int[] values, final int difference) {

    Collection&lt;Integer&gt; valuesSet = Arrays.stream(values).boxed().collect(Collectors.toSet());

    return valuesSet.stream()
            .map(v -&gt; v - difference)
            .filter(valuesSet::contains)
            .map(v -&gt; new int[] { v, v + difference })
            .toArray(size -&gt; new int[size][2]);
}