HomeSoftware EngineeringThe Distinction of two in Java

# The Distinction of two in Java

## The problem#

The target is to return all pairs of integers from a given array of integers which have a distinction of two.

The ensuing array needs to be sorted in ascending order of values.

Assume there aren’t any duplicate integers within the array. The order of the integers within the enter array mustn’t matter.

Examples:

``````[1, 2, 3, 4]  ought to return [[1, 3], [2, 4]]
[4, 1, 2, 3]  also needs to return [[1, 3], [2, 4]]
[1, 23, 3, 4, 7] ought to return [[1, 3]]
[4, 3, 1, 5, 6] ought to return [[1, 3], [3, 5], [4, 6]]
``````

## The answer in Java code#

Choice 1:

``````import java.util.*;
import java.util.stream.*;

public class Problem {
public static int[][] twosDifference(int[] a) {
var s = Arrays.stream(a).boxed().gather(Collectors.toSet());
return Arrays.stream(a).boxed().filter(x -> s.accommodates(x + 2)).sorted().map(x -> new int[]{x, x + 2}).toArray(int[][]::new);
}
}
``````

Choice 2:

``````import static java.util.Arrays.*;
import java.util.*;

public class Problem {
public static int[][] twosDifference(int[] array) {
kind(array);
last Record<int[]> consequence = new LinkedList<>();
for (int quantity : array) {
int search = quantity - 2;
if (binarySearch(array, search) >= 0) {
}
}
return consequence.toArray(new int[][] {});
}
}
``````

Choice 3:

``````import static java.util.stream.IntStream.of;
import static org.apache.commons.lang3.ArrayUtils.accommodates;

interface Problem {
static int[][] twosDifference(int[] array) {
return of(array).filter(i -> accommodates(array, i + 2)).sorted().mapToObj(i -> new int[]{i, i + 2}).toArray(int[][]::new);
}
}
``````

## Check circumstances to validate our resolution#

``````import org.junit.Check;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class Checks {
@Check
public void sample_tests() {
assertArrayEquals(
new int[][]{{1, 3}, {2, 4}},
Problem.twosDifference(new int[]{1, 2, 3, 4})
);
assertArrayEquals(
new int[][]{{1, 3}, {4, 6}},
Problem.twosDifference(new int[]{1, 3, 4, 6})
);
}
}
``````
RELATED ARTICLES