How can i avoid the inner loop and write this 'allocation' only with stream features?
Edit: I want a list of all unique pairs catenated together, stored in l2.
Example: Input: String[] l = { "a", "a", "b", "c", "d", "d", "d", "d", "a", "a", "b", "b", "c", "d" };, output: [a, a, b, c, d, d, b, b, c, d].
String[] l = { "a", "a", "b", "c", "d", "d", "d", "d", "a", "a" };
String[] l2 =
IntStream.iterate(0, i -> i < l.length, i -> i + 2)
.mapToObj(i -> Objects.hash(l[i], l[i + 1]))
.distinct()
.map(h -> {
for (int j = 0; j < l.length; j += 2) {
if (h == Objects.hash(l[j], l[j + 1])) {
return new String[] { l[j], l[j + 1] };
}
}
return null;
})
.flatMap(Arrays::stream)
.toArray(String[]::new);
System.out.println(Arrays.toString(l2));